简体   繁体   English

Powershell无法调用.net类的方法

[英]Powershell can't invoke .net class' method

I wrote powershell script which contains this code: 我编写了包含以下代码的powershell脚本:
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'. 它在我的电脑上可以正常工作,但在另一台电脑(相同的.net框架版本)上却失败,并出现错误: 方法调用失败,因为[System.IO.File]不包含名为“ ReadLines”的方法。 What's wrong? 怎么了?

Unless you have a strong reason to use [System.IO.File]::ReadLines , consider PowerShell's Get-Content cmdlet instead: 除非您有充分的理由使用[System.IO.File]::ReadLines ,否则请考虑使用PowerShell的Get-Content cmdlet:

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. 另外, foreachForEach-Object的别名,您可以通过管道传递到它。 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? 您确定所有涉及的计算机都已安装.net 4.0吗? And that Powershell is version 3.0 or at least 2.0 with powershell.exe.config customized to use .Net 4.0 ? 而且Powershell是3.0版或至少是2.0并且自定义了powershell.exe.config以使用.Net 4.0?

File.ReadLines starts only from .Net 4.0. File.ReadLines仅从.Net 4.0开始。

Why not use get-content cmdlet? 为什么不使用get-content cmdlet?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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