Search code examples
powershellrunspace

Pass information between independently running Powershell scrips


Sorry for being wage before. I'll try again:

The circumstances are too complicated to explain, but basically the problem is:

  • how to pass a string (max 20 chars) from one script, to another script running on the same machine.
  • the two scripts are running continuously in the background, on the same machine, under the same user context, but can not be combined.
  • I can not dot-source one script in the other.

I have done it by having one script create a file with the string in it, in a directory monitored by the other script. So when it appears, the other script reads the information. It works, but it feels "dirty". :)

I was wondering if there is a "best practice"-way to pass information between scripts or at least a more elegant way.

Thanks.


Solution

  • There are several ways for enabling two continuously running processes on the same host to communicate with each other, for instance named pipes:

    # named pipe - server
    $name = 'foo'
    $namedPipe = New-Object IO.Pipes.NamedPipeServerStream($name, 'Out')
    $namedPipe.WaitForConnection()
    
    $script:writer = New-Object IO.StreamWriter($namedPipe)
    $writer.AutoFlush = $true
    $writer.WriteLine('something')
    $writer.Dispose()
    
    $namedPipe.Dispose()
    
    # named pipe - client
    $name = 'foo'
    $namedPipe = New-Object IO.Pipes.NamedPipeClientStream('.', $name, 'In')
    $namedPipe.Connect()
    
    $script:reader = New-Object IO.StreamReader($namedPipe)
    $reader.ReadLine()
    $reader.Dispose()
    
    $namedPipe.Dispose()
    

    or TCP sockets:

    # TCP socket - server
    $addr = [ipaddress]'127.0.0.1'
    $port = 1234
    
    $endpoint = New-Object Net.IPEndPoint ($addr, $port)
    $server = New-Object Net.Sockets.TcpListener $endpoint
    $server.Start()
    $cn = $server.AcceptTcpClient()
    
    $stream = $cn.GetStream()
    $writer = New-Object IO.StreamWriter($stream)
    $writer.WriteLine('something')
    $writer.Dispose()
    
    $server.Stop()
    
    # TCP socket - client
    $server = '127.0.0.1'
    $port   = 1234
    
    $client = New-Object Net.Sockets.TcpClient
    $client.Connect($server, $port)
    $stream = $client.GetStream()
    
    $reader = New-Object IO.StreamReader($stream)
    $reader.ReadLine()
    $reader.Dispose()
    
    $client.Dispose()