Home > Uncategorized > Powershell to find the next available port

Powershell to find the next available port

Every now and then I’m installing service application on a development machine, and I just want to find the next available port that I can use. Here is a handy Powershell script to do that, which can be easily run as part of a deployment script.

param([int]$port = $(throw("Port required.")))
$isInUse = $FALSE
	trap [System.Net.Sockets.SocketException]
		write-host "Unable to open socket on port $port."
		$script:port = $script:port + 1
		$script:isInUse = $TRUE;

	$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Any, $port)
	write-host "Socket opened successfully on port $port."
	$isInUse = $FALSE
return $port

The easiest way to call this is to include it directly in another powershell script, but if you want to save this as a script that you can call from a different script as a cmdlet, you need to execute this command first, which allows execution of unsigned scripts from the local machine.

set-ExecutionPolicy RemoteSigned

After you’re done with your processing, you may want to set this back to the default restricted setting:

set-ExecutionPolicy Restricted

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: