Private/WebUtil.ps1
Function Get-FreeWebPort { <# .Synopsis Find a free port for web application. .Description Find a free port for web application, starting from a given port, and increment if needed. .Parameter startingPort The port to start with. .Example # find a free port starting with 8090 Get-FreeWebPort 8090 #> [cmdletbinding()] [OutputType([int])] param( [int] $startingPort ) Process { $usedPorts = @() Import-Module WebAdministration foreach ($bind in (Get-WebBinding).bindingInformation) { $port = Parse-Binding $bind $usedPorts += $port } $choosenPort = $startingPort while ($usedPorts.contains($choosenPort)) { $choosenPort += 1 } return $choosenPort } } function Parse-Binding($bind) { $startIndex = $bind.indexof(':')+1 $endIndex = $bind.lastindexof(':') $port = $bind.Substring($startIndex, ($endIndex-$startIndex)) return $port } |