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
    {
        Write-Output "Get used ports from IIS"
        
        $usedPorts = @()
        Import-Module WebAdministration
        
        foreach ($bind in (Get-WebBinding).bindingInformation) {
            $startIndex = $bind.indexof(':')+1
            $endIndex = $bind.lastindexof(':')
            $port = $bind.Substring($startIndex, ($endIndex-$startIndex))
            Write-Output "Found port "$port
            $usedPorts += [int] $port 
        }
        
        Write-Output "Check if $startingPort is used in IIS"
        
        $choosenPort = $startingPort
        while ($usedPorts.contains($choosenPort)) {
            $choosenPort += 1
        }
        
        Write-Output "Choosen port "$choosenPort
        return [int] $choosenPort
    }
}