8

I've noticed that when we create a firewall rule through netsh advfirewall firewall, it can be run multiple times, creating multiple identical firewall rules.

Is there any way of checking if the firewall rule exists before attempting to create a new one?

ShaneC
  • 2,237
  • 2
  • 32
  • 53

5 Answers5

5

I managed to get this going through PowerShell's Network Security Cmdlets, the following code will check for a named firewall rule along with a specified local port, if it finds an entry, it does not create the rule. If it does not find an entry, it will create the rule

$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"
}
ShaneC
  • 2,237
  • 2
  • 32
  • 53
5

Check if rule "myrule" not exists

netsh advfirewall firewall show rule name="myrule" | findstr "no rules"
Oleg
  • 51
  • 1
  • 2
  • 2
    It is not safe to parse the result text for english words, because the user might have a different OS langauge - or the wording might eventually change. – bytecode77 Sep 28 '20 at 06:41
5

To expand on @Oleg's answer, here is what I use. Replace the ... according to the criteria for your rule.

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! ...
)
ouk
  • 395
  • 5
  • 7
2

why nobody mentioned the || operator for failures in batch? the opposite of the && success operator

:: (if command errors) || (exec this command)
netsh advfirewall firewall show rule name="myrule" >nul || netsh advfirewall firewall add rule name="myrule" ...
my2cents
  • 103
  • 5
0
Get-Command -Module NetSecurity
get-help Get-NetFirewallRule -full
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • 4
    [answer], [tour] – Yunnosch Jul 26 '19 at 16:02
  • 2
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – CertainPerformance Jul 26 '19 at 23:00