PowerShell中的某些.NET 4.0类似乎不起作用

Mat*_*zke 4 .net powershell

我正在创建一个使用一些System.Diagnostics.ProcessSystem.Diagnostics.ProcessStartInfo类的powershell脚本.

这些类完全正常,如下所示:

$processInfo = new-object System.Diagnostics.ProcessStartInfo

$processInfo.FileName = "dism.exe"
$processInfo.UseShellExecute = $false
$processInfo.RedirectStandardOutput = $true
$processInfo.Arguments = "/Apply-Image /ImageFile:C:\images\Win864_SL-IN-837.wim /ApplyDir:D:\ /Index:1"

$process = new-object System.Diagnostics.Process
$process.StartInfo = $processInfo
Run Code Online (Sandbox Code Playgroud)

但是,我也想使用System.IO.StreamReader类,但是当我像这样尝试EXACT相同的东西时:

$stream = new-object System.IO.StreamReader
Run Code Online (Sandbox Code Playgroud)

或者像这样

$stream = new-object System.IO.StreamReader $process.FileName
Run Code Online (Sandbox Code Playgroud)

我收到错误:

New-Object : Constructor not found. Cannot find an appropriate constructor for type System.IO.StreamReader.
At C:\Users\a-mahint\Documents\Testing\inter.ps1:17 char:21
+ $stream = new-object <<<<  System.IO.StreamReader
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
Run Code Online (Sandbox Code Playgroud)

我一直想弄清楚这半小时......发生了什么事?这两个类都是.NET 4.0的一部分

Tru*_*ill 6

StreamReader没有no-arg构造函数,并且您没有提供任何参数.

在C#中尝试一下.你会得到

'System.IO.StreamReader'不包含带0参数的构造函数

相反,试试吧

$stream = new-object System.IO.StreamReader "foo.txt"
Run Code Online (Sandbox Code Playgroud)

哪里foo.txt是现有文件.

请注意,它没有带参数类型的构造函数ProcessStartInfo,这就是传递$process.StartInfo不起作用的原因.相反,尝试传球$processInfo.FileName.