如何将参数作为类而不是字符串传递给New-Object?

时间:2018-04-20 16:45:00

标签: c# powershell powershell-v3.0

我似乎无法将$ outputStream作为Stream传递给StreamWritter构造函数。它以字符串形式传递,然后调用错误的构造函数,期望字符串不流。

$tcpClient = New-Object System.Net.Sockets.TCPClient        
$connect = $tcpClient.BeginConnect("localhost", 8080, $null, $null)
$success = $connect.AsyncWaitHandle.WaitOne($testTimeoutMs, $true)
[System.Net.Sockets.NetworkStream]$outputStream = $tcpClient.GetStream()
$writer = New-Object System.IO.StreamWriter -ArgumentList $outputStream, [System.Text.Encoding].ASCII

我想调用这个(https://msdn.microsoft.com/en-us/library/3aadshsx(v=vs.110).aspx)构造函数,但它调用一个带字符串参数而不是Stream。

这会导致此错误:

New-Object : Exception calling ".ctor" with "2" argument(s): "The process cannot access the file 'C:\Users\Maciej\System.Net.Sockets.NetworkStream' because it is being used by anothe
r process."
At line:1 char:12
+  $writer = New-Object System.IO.StreamWriter -ArgumentList $outputStr ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

如何强制将此参数作为Stream传递给字符串?

1 个答案:

答案 0 :(得分:4)

您的问题是尝试使用错误的语法访问[Encoding]类的静态成员:

[Text.Encoding].ASCII

在PowerShell中,您可以使用以下语法访问类型静态成员:

[Text.Encoding]::ASCII

此对象的[System.Text.ASCIIEncoding]类型根据.GetType()继承自[System.Text.Encoding]并且应该解析您收到的constructor errors

$tcpClient = New-Object -TypeName 'System.Net.Sockets.TCPClient'

$connect = $tcpClient.BeginConnect('localhost', 8080, $Null, $Null)
$success = $connect.AsyncWaitHandle.WaitOne($testTimeoutMs, $True)

$outputStream = $tcpClient.GetStream()
$writer = New-Object -TypeName 'System.IO.StreamWriter' -ArgumentList @($outputStream, [System.Text.Encoding]::ASCII)

作为旁注,在v5 +中,您可以原生地调用构造函数方法:

$streamWriter = [IO.StreamWriter]::new($outputStream, [Text.Encoding]::ASCII)