【问题标题】:Powershell can't invoke .net class' methodPowershell 无法调用 .net 类的方法
【发布时间】:2014-04-28 11:20:30
【问题描述】:

我编写了包含以下代码的 powershell 脚本:
foreach ($line in [System.IO.File]::ReadLines ...
它在我的电脑上运行良好,但在另一台(相同的 .net 框架版本)上失败并出现错误: 方法调用失败,因为 [System.IO.File] 不包含名为“ReadLines”的方法。出了什么问题?

【问题讨论】:

  • 第一个例子说 ReadLine... 你的错误说 ReadLines 带有一个 S。这是错字还是原因?
  • @Knuckle-Dragger 抱歉,它是 ReadLines。我已经更正了。

标签: powershell


【解决方案1】:

除非您有充分的理由使用 [System.IO.File]::ReadLines,否则请考虑使用 PowerShell 的 Get-Content cmdlet:

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

另外,foreachForEach-Object 的别名,您可以通过管道访问它。管道中的每个对象都称为 $_。因此,您可以编写一个脚本块,它将针对文件中的每一行运行,如下所示:

Get-Content .\my\file.txt | { Write-Output $_ }

【讨论】:

    【解决方案2】:

    您确定所有涉及的计算机都安装了.net 4.0 吗? 并且那个 Powershell 是 3.0 或至少 2.0 版本,其中 powershell.exe.config 定制为使用 .Net 4.0?

    File.ReadLines 仅从 .Net 4.0 开始。

    为什么不使用get-content cmdlet?

    【讨论】:

    • 我的 ReadLines 解决方案在我的电脑 (Windows 8) 上运行良好,另一台电脑安装了 Windows7。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2019-06-16
    • 1970-01-01
    相关资源
    最近更新 更多