PowerShell NamedPipe管道的StreamReader的编码?

时间:2014-06-11 06:42:18

标签: powershell named-pipes

抱歉对这个愚蠢的烟斗感到讨厌 - 但我需要它:(

我定义了管道及其读者:

 $Enc = [System.Text.Encoding]::ASCII # UTF8 #  
 $Buf = new-object byte[] 4096
 $pipeDir  = [System.IO.Pipes.PipeDirection]::InOut
 $pipeMsg  = [System.IO.Pipes.PipeTransmissionMode]::Byte  
 $pipeOpti = [System.IO.Pipes.PipeOptions]::Asynchronous 
 $pipe = New-Object system.IO.Pipes.NamedPipeServerStream(` 
                $pipeName, $pipeDir, 1, $pipeMsg, $pipeOpti )
 $pr = new-object System.IO.StreamReader $pipe $Enc $false 4096 $true
 $pr

我收到了错误

 No Position-Parameter found that would accept "System.Text.ASCIIEncoding" at ..
 + $pr = new-object <<<<  System.IO.StreamReader $pipe $Enc $false 4096 $true
       + CategoryInfo          : InvalidArgument: (:) [New-Object], 
                                 ParameterBindingException
       + FullyQualifiedErrorId : PositionalParameterNotFound,
                                 Microsoft.PowerShell.Commands.NewObjectCommand

 CurrentEncoding : System.Text.UTF8Encoding
 BaseStream      : System.IO.Pipes.NamedPipeServerStream
 EndOfStream     : True

但我更喜欢(需要?)ASCII:
怎么办?

如果我像这样定义Reader(否则它不会读取任何内容):

 $pr = new-object System.IO.StreamReader $pipe

我得到了阅读功能

 readReader $pr, $Buff, $Enc
 ...
 #(in that function:)
 try {
      $read = $r.Read($b, 0, $b.Length)
        if ($read -ne 0) { Write-Host "READ: $read  $($b[0..$($read-1)])" }
        if($read -gt 0) {
                 $foundmore = $true
                 $got += $e.GetString($b, 0, $read)
                 $nTry = -1
                 Write-Host "rdMsg: rd:$read, $got" 
        }
 } catch { $foundMore = $false; $read = 0; }

我可以阅读此输出:

  READ: 4  0 0 0 0
  rdMsg: rd:4,     
  READ: 27  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  rdMsg: rd:27,     

最后,脚本在读取时挂起:

     $read = $r.Read($b, 0, $b.Length)  

直到管道从另一侧关闭

我的错误在哪里? - 请你 提前致谢, Gooly

1 个答案:

答案 0 :(得分:0)

这一行:

$pr = new-object System.IO.StreamReader $pipe $Enc $false 4096 $true

应写成:

$pr = new-object System.IO.StreamReader($pipe, $Enc, $false, 4096, $true)