Communicating Between Multiple PowerShells via UDP

by May 9, 2012

Assume you want to send some information to another PowerShell session, or you'd like to have one session wait until another is ready. Here are two simple functions that allow you to send and receive text information across PowerShell sessions using UDP:

function Send-Text($Text='Sample Text', $Port=2500) {
    $endpoint = New-Object System.Net.IPEndPoint ([IPAddress]::Loopback,$Port)
    $udpclient= New-Object System.Net.Sockets.UdpClient
    $bytes=[Text.Encoding]::ASCII.GetBytes($Text)
    $bytesSent=$udpclient.Send($bytes,$bytes.length,$endpoint)
    $udpclient.Close()
}


function Start-Listen($Port=2500) {
    $endpoint = New-Object System.Net.IPEndPoint ([IPAddress]::Any,$Port)
    $udpclient= New-Object System.Net.Sockets.UdpClient $Port
    $content=$udpclient.Receive([ref]$endpoint)
    [Text.Encoding]::ASCII.GetString($content)
} 

Try it and launch two PowerShell consoles. Execute this code in both of them. Then, in one session call Start-Listen. Optionally you can change the network port.

The session now waits on the port specified. In your other shell, call this to wake up the listening shell and send over some text:

PS> Send-Text 'Hello Wake Up!'

Twitter This Tip! ReTweet this Tip!