重复的Windows防火墙规则(Netsh AdvFirewall防火墙)



我注意到,当我们通过netsh advfirewall firewall创建防火墙规则时,它可以运行多次,创建多个相同的防火墙规则。

在尝试创建一个新的防火墙规则之前,是否有办法检查防火墙规则是否存在?

检查规则"myrule"是否不存在

netsh advfirewall firewall show rule name="myrule" | findstr "no rules"

我设法通过PowerShell的网络安全cmdlet来实现这一点,下面的代码将检查指定的防火墙规则以及指定的本地端口,如果它找到一个条目,它不会创建规则。如果没有找到条目,它将创建规则

$firewallPort = ""
$firewallRuleName = ""
write-host "Checking for '$firewallRuleName' firewall rule on port '$firewallPort' now...."
if ($(Get-NetFirewallRule –DisplayName $firewallRuleName | Get-NetFirewallPortFilter | Where { $_.LocalPort -eq $firewallPort }))
{
    write-host "Firewall rule for '$firewallRuleName' on port '$firewallPort' already exists, not creating new rule"
}
else
{
    write-host "Firewall rule for '$firewallRuleName' on port '$firewallPort' does not already exist, creating new rule now..."
    New-NetFirewallRule -DisplayName $firewallRuleName -Direction Inbound -Profile Domain,Private,Public -Action Allow -Protocol TCP -LocalPort $firewallPort -RemoteAddress Any
    write-host "Firewall rule for '$firewallRuleName' on port '$firewallPort' created successfully"
}

为了扩展@Oleg的答案,以下是我使用的。更换…根据您的规则的标准。

set name="my rule"
netsh advfirewall firewall show rule name=!name! >nul
if errorlevel 1 (
    echo Adding firewall rule !name!
    netsh advfirewall firewall add rule name=!name! ...
)

为什么没有人提到批处理失败的||操作符?&&成功操作符

:: (if command errors) || (exec this command)
netsh advfirewall firewall show rule name="myrule" >nul || netsh advfirewall firewall add rule name="myrule" ...
Get-Command -Module NetSecurity
get-help Get-NetFirewallRule -full

相关内容

  • 没有找到相关文章

最新更新