简体   繁体   中英

Powershell can't invoke .net class' method

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?

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 $_ }

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM