Check availability of Remote Desktop Services or XenApp with PowerShell

Here’s a way to check port availability with PowerShell.

$server = “server1”

$port = 3389

$(new-object Net.Sockets.TcpClient).Connect($server, $port)

This initiates a connection to $server on port number $port.  If the connection is successful then nothing happens.  If the connection fails then an error exception is generated of the type ‘System.Net.Sockets.SocketException’. So this has a lot of valuable applications in and of itself, but where I found it particularly useful was in testing the availability of RDP/ICA after rebooting a Remote Desktop Services server or XenApp server.

To do this, I use the following do/until loop:

$server = “Server1”

        # Test ICA on ports 2598 and 1494
        $(new-object Net.Sockets.TcpClient).Connect($server, $port1)
        $(new-object Net.Sockets.TcpClient).Connect($server, $port2)
        # Test RDP on port 3389
        $(new-object Net.Sockets.TcpClient).Connect($server, $port3)
        # Sets $isup to true by default
        $isup = $true
    catch [System.Net.Sockets.SocketException]
        $isup = $false

So the script tests on ports 2598, 1494, and 2278 and sets the $isup variable to $false by default.  If everything connects then the loop ends and the script continues, but if an error exception is generated by any of the three ports then a socket error is detected and the loop continues.  As soon as all three ports are responding then you should be able to connect using RDP/ICA.

I love PowerShell.

    • Chris
    • August 28th, 2012

    Nice code. I needed this. thanks!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: