title: PowerShell Named Pipe: no connection?
body: <p>I need a named pipe to read and write.</p>
  
  <p>In a program I create the pipe server using from <strong>kernel32.dll</strong>:</p>
  
  <pre><code>string PipeName = "\\\\.\\pipe\\myMT4"; 
  int PipeMode = PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_WAIT; # tried too: PIPE_NOWAIT
  int hPipe = CreateNamedPipeW(
              PipeName,
              PIPE_ACCESS_DUPLEX,
              PipeMode,
              PIPE_UNLIMITED_INSTANCES,1024,1024,
              NMPWAIT_USE_DEFAULT_WAIT,NULL);
  </code></pre>
  
  <p>The handle hPipe is valid - every things seems to be ok here!</p>
  
  <p>But in a PowerShell-script I want to open a client, connect and open the writer - <br>
  and cannot connect => timed out<br></p>
  
  <pre><code>function connect{
      Param ([PSObject] $h)
      ...
      $h.Pipe = New-Object -TypeName System.IO.Pipes.NamedPipeClientStream "\\.\pipe\PipeTest"
      $h.Pipe.Connect( 5000 )
      $h.Writer = New-Object -TypeName System.IO.StreamWriter $h.Pipe, $h.Encode 
  </code></pre>
  
  <p>I really would prefer this way to have a similar access when reading and writen<br>
  either from/to the pipe and sockets e.g.:</p>
  
  <pre><code>function write{
      Param ([PSObject] $h, [string] $line )
    try {
          $h.Writer.Write($line) 
      }       
  </code></pre>
  
  <p>What is wrong?
  Thanks in advance,
  Gooly.</p>
  
  <p>PS: 
  It seems that the program cannot deal with pipe-servers - I have to open a pipe-client, and that works but that causes other problems:</p>
  
  <p>I define for the PowerShell-pipe-server :</p>
  
  <pre><code> $pipeName = "testpipe"
   $pipeDir  = [System.IO.Pipes.PipeDirection]::InOut
   $pipeMsg  = [System.IO.Pipes.PipeTransmissionMode]::Message
   $pipeOpti = [System.IO.Pipes.PipeOptions]::Asynchronous
   $pipe = New-Object system.IO.Pipes.NamedPipeServerStream( 
                    $pipeName, $pipeDir, 1, $pipeMsg, $pipeOpti )
   $pipe.WaitForConnection() # 
   $sw = new-object System.IO.StreamWriter $pipe
   $sw.AutoFlush = $true
   $sw.WriteLine("Server pid is $pid")
   $sw.Dispose()
   $pipe.Dispose()
  </code></pre>
  
  <p>1) My first problem is now that the powerShell-pipe-server is blocked by </p>
  
  <pre><code> $pipe.WaitForConnection()
  </code></pre>
  
  <p>until a client connects but it must handle 2 different sockets independently meanwhile and </p>
  
  <p>2) if the client closes the connection I was unable to tell the client to open the same pipe again and the client gets the Windows-error: ERROR_PIPE_BUSY 231</p>
  
  <p>Form the program I connect to the server with the kernel32.dll-function:</p>
  
  <pre><code> int CallNamedPipeW(string PipeName, 
             string outBuffer, int outBufferSz, 
             uint&amp; inBuffer[], int inBufferSz, 
             int&amp; bytesRead[], int timeOut
   );
  </code></pre>
  
  <p>Any ideas?</p>