R – PowerShell Script to Disable/Re-enable a TCP/IP Port

powershellscriptingtcp

Is there a way to disable and re-enable a known TCP/IP port in PowerShell?

Best Answer

I'll make the blind assumption that you are talking about disabling & enabling TCP/IP sockets that are hosted by IIS. (Not, say, looking for ways to block/unblock things at the Firewall level, or something else entirely.) In that case, I happen to have the necessary scripts lying around...

# Get the IIsWebServer and IIsWebServerSetting WMI objects matching a display name, and combine them into one object
function Get-IIsWeb
{
    param (
        [string] $displayName = "",
        [string] $computer = "localhost"
    )

    if ($displayName -eq "")
        { $filter = "" }
    else
        { $filter = "ServerComment='$displayName'"}    

    Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsWebServerSetting" -filter $filter -computer $computer -authentication 6 | % {
        $temp = $_
        Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsWebServer" -filter "Name='$($_.Name)'" -computer $computer -authentication 6 | 
            add-member -membertype NoteProperty -name Settings -value $temp -passthru
    }
}

# Stop all websites on a given computer that are bound to the specified port, unless they are scoped to a 
# host header or IP address
function Stop-WebsiteOnPort
{
    [CmdletBinding()]    
    param (
        [Parameter(Mandatory=$true, valuefrompipeline=$true)]
        [int] $port,
        [Parameter(Position=0)]
        [string] $computer = "localhost",
        [Parameter()]
        [string] $hostName = $null,
        [Parameter()]
        [string] $ip = $null
    )

    begin { $websites = Get-IIsWeb -computer $computer }

    process
    {
        # I don't think you can do this filter in WQL
        $websites | 
          ? {
                ( $_.settings.serverbindings | ? {$_.port -eq $port -and $_.Hostname -eq $hostName -and $_.IP -eq $ip} | measure).count -gt 0
            } |
          % {
                $_.stop()
            }               
    }
}

The actual WMI code to re-enable a site is pretty much identical to the code for stopping one seen above. However, you'll need to do a little more work: there could be arbitrarily many sites configured to use a given port, but only 1 can run at a time. Either you'll need an additional parameter from the user, or some heuristic for picking the "right" site.