用于禁用/重新启用TCP / IP端口的PowerShell脚本

时间:2009-09-02 22:10:45

标签: powershell scripting tcp

有没有办法在PowerShell中禁用和重新启用已知的TCP / IP端口?

1 个答案:

答案 0 :(得分:0)

我会盲目地假设你在谈论禁用和放弃启用IIS托管的TCP / IP套接字。 (不是说,寻找阻止/取消阻止防火墙级别的东西的方法,或完全不同的东西。)在这种情况下,我碰巧有必要的脚本......

# 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()
            }               
    }
}

重新启用网站的实际WMI代码与停止上述代码的代码非常相似。但是,您需要做更多的工作:可能会有任意多个站点配置为使用给定端口,但一次只能运行1个。要么您需要来自用户的附加参数,要么需要一些启发式来挑选“正确”的网站。