Created
March 28, 2022 09:26
-
-
Save nichollsc81/33c3702ac16e56b5f910000b2b2810ac to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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