#Requires -Version 5.1 #Requires -RunAsAdministrator function Add-ExcludedPortRange { [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] [int] $StartPort, [int] $NumberOfPorts = 1 ) $ipList = @("ipv4", "ipv6") $protoList = @("tcp", "udp") function LogAndRunCmd ([string] $Cmd, [string[]] $CmdArgs) { Write-Output "> $Cmd $($CmdArgs -join " ")" & $Cmd @CmdArgs Write-Output "" } $msg = "stopping winnat" if ($PSCmdlet.ShouldProcess($msg)) { Write-Output "${msg}..." LogAndRunCmd "net" @("stop", "winnat") } foreach ($ip in $ipList) { foreach ($proto in $protoList) { $msg = "show excludedportrange: ${ip}/${proto}" Write-Output "${msg}..." LogAndRunCmd "netsh" @("interface", $ip, "show", "excludedportrange", "protocol=${proto}") $msg = "add excludedportrange: ${ip}/${proto} -> ${StartPort}-$($StartPort + $NumberOfPorts - 1)" if ($PSCmdlet.ShouldProcess($msg)) { Write-Output "${msg}..." LogAndRunCmd "netsh" @("interface", $ip, "add", "excludedportrange", "protocol=${proto}", "startport=${StartPort}", "numberofports=${NumberOfPorts}") } } } $msg = "starting winnat" if ($PSCmdlet.ShouldProcess($msg)) { Write-Output "${msg}..." LogAndRunCmd "net" @("start", "winnat") } }