This has been sitting in my drafts for some time. Based on some of my experiences this week and some of the stuff we’re trying to do at work, I’ll probably have more PowerShell soon. Unfortunately.

RandomizedPort.psm1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<#
.SYNOPSIS
Generates a random port number in a (hopefully) open range.
.LINK
https://www.cymru.com/jtk/misc/ephemeralports.html
#>
Function Get-RandomPort
{
return Get-Random -Max 32767 -Min 10001;
}

Function Test-PortInUse
{
Param(
[Parameter(Mandatory=$true)]
[Int] $portToTest
);
$count = netstat -aon | find `":$portToTest `" /c;
return [bool]($count -gt 0);
}

Function Get-RandomUsablePort
{
Param(
[Int] $maxTries = 100
);
$result = -1;
$tries = 0;
DO
{
$randomPort = Get-RandomPort;
if (-Not (Test-PortInUse($randomPort)))
{
$result = $randomPort;
}
$tries += 1;
} While (($result -lt 0) -and ($tries -lt $maxTries));
return $result;
}