添加或更新防火墙规则

添加或更新防火墙规则

我在 powershell 脚本中使用以下命令添加防火墙规则以便为 Web 服务器打开端口 80。

netsh advfirewall firewall add rule name= "RemoteData Open Port 80 in" dir=in action=allow protocol=TCP localport=80

但是,这总是会添加一条规则,这导致我在再次运行脚本时创建后续规则。我不想这样,我希望即使多次执行脚本也只创建一条规则。

在此处输入图片描述

我也尝试使用set new而不是add,但这要求规则已经存在 - 如果找不到这样的规则,它就不会添加新规则:

netsh advfirewall firewall set new rule name= "RemoteData Open Port 80 in" dir=in action=allow protocol=TCP localport=80

在此处输入图片描述

我正在使用的 Powershell 脚本没什么有趣的:

function New-FirewallRule
{
    # NOTE add creates a new rule each time
    Write-Host Creating new firewall rule '"RemoteData Open Port 80 in"'
    & netsh advfirewall firewall set rule name= "RemoteData Open Port 80 in" dir=in action=allow protocol=TCP localport=80
   
    # Below is uncommented and can be uncommented when needed.
    # Write-Host Creating new firewall rule '"RemoteData Open Port 80 out"'
    # & netsh advfirewall firewall add rule name= "RemoteData Open Port 80 out" dir=out action=allow protocol=TCP localport=80
}

function Run-Main {
    
    Run-PreFlightCheck
    
    New-FirewallRule
}

答案1

您可以在 PowerShell 脚本中使用此代码片段来检查规则是否已存在:

if (netsh advfirewall firewall show rule name="RemoteData Open Port 80 in" -contains "No rules match the specified criteria.")
{
  netsh advfirewall firewall set new rule name= "RemoteData Open Port 80 in" dir=in action=allow protocol=TCP localport=80
}

答案2

您可以首先检查防火墙规则是否已经存在,如果不存在则创建它。

netsh advfirewall firewall show rule "RemoteData Open Port 80 in"

如果不存在,你会得到

No rules match the specified criteria.

如果存在,则返回该规则的属性。

答案3

harrymc 的答案有效。我选择事先删除该规则,以便与脚本的另一部分保持一致。以下是经过修改的代码:

function New-FirewallRule
{
    # NOTE add creates a new rule each time
    Write-Host Creating new firewall rule $FireWallRuleName

    if ((& netsh advfirewall firewall show rule name= `"$FireWallRuleName`") -notcontains "No rules match the specified criteria.")
    {
        Write-Host $FireWallRuleName already exists and will be deleted prior to starting
        Write-Host (& netsh advfirewall firewall delete rule name= `"$FireWallRuleName`")
    }

    Write-Host (& netsh advfirewall firewall add rule name= "RemoteData Open Port 80 in" dir=in action=allow protocol=TCP localport=80)
   
    # Below is uncommented and can be uncommented when needed.
    # Write-Host Creating new firewall rule '"RemoteData Open Port 80 out"'
    # & netsh advfirewall firewall add rule name= "RemoteData Open Port 80 out" dir=out action=allow protocol=TCP localport=80
}

请注意,如果您有多个同名规则,这将删除所有规则。我认为这是一项功能。

相关内容