1

I wrote powershell script which contains this code:
foreach ($line in [System.IO.File]::ReadLines ...
It works fine on my pc but fails on another one (the same .net framework version) with error: Method invocation failed because [System.IO.File] doesn't contain a method named 'ReadLines'. What's wrong?

2
  • 1
    First example says ReadLine... your error says ReadLines with an S. Is that a typo or the cause ? Commented Mar 21, 2014 at 8:26
  • @Knuckle-Dragger sorry, it's ReadLines. I've corrected this. Commented Mar 21, 2014 at 8:36

2 Answers 2

2

Unless you have a strong reason to use [System.IO.File]::ReadLines, consider PowerShell's Get-Content cmdlet instead:

foreach ($line in Get-Content .\my\file.txt)
{
   Write-Output $line
}

Also, foreach is an alias for ForEach-Object and you can pipe to it. Each object in the pipeline is referred to as $_. So you can write a script block which will run for every line in your file like this:

Get-Content .\my\file.txt | { Write-Output $_ }
Sign up to request clarification or add additional context in comments.

Comments

1

Are you sure that all involved computers are with .net 4.0 installed? And that Powershell is version 3.0 or at least 2.0 with powershell.exe.config customized to use .Net 4.0 ?

File.ReadLines starts only from .Net 4.0.

Why not use get-content cmdlet?

1 Comment

My solution with ReadLines works fine on my pc (Windows 8), another pc has installed Windows7.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.