private/get/Get-EphemeralPort.ps1
function Get-EphemeralPort { [CmdletBinding()] [OutputType([int])] param() $attemptLimit = 50 $minPort = 5000 $maxPort = 65535 $attempt = 0 $result = -1 while ($result -eq -1 -and $attempt -lt $attemptLimit) { $port = Get-Random -Minimum $minPort -Maximum $maxPort if (Test-PortAvailable -Port $port) { $result = $port } $attempt++ } if ($result -gt 0) { return $result } else { throw "Failed to allocate a local network port after $attemptLimit attempts." } } |