Skip to content

Instantly share code, notes, and snippets.

@nichollsc81
Created March 28, 2022 09:26
Show Gist options
  • Save nichollsc81/33c3702ac16e56b5f910000b2b2810ac to your computer and use it in GitHub Desktop.
Save nichollsc81/33c3702ac16e56b5f910000b2b2810ac to your computer and use it in GitHub Desktop.
Function Get-RandomPort
{
return Get-Random -Max 32767 -Min 30000;
}
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;
}
Get-RandomUsablePort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment