PowerShell check if firewall rule exists before create
This post describes how to use PowerShell to check if a firewall rule exists in Windows.
This can be very useful if you're creating a PowerShell script which creates Windows Firewall rules multiple times and you don't want to end up adding lots of duplicate firewall rules!
This can be very useful if you're creating a PowerShell script which creates Windows Firewall rules multiple times and you don't want to end up adding lots of duplicate firewall rules!
Command
Using the netsh command, you can check for the existence of rules e.g. with a particular name:
netsh advfirewall firewall show
rule name="**
TCP Port 1433"This returns "No rules match the specified criteria." if no rules are found.
Solution
Put the netsh command in an if statement to check if the rule exists before creating it:
if((netsh advfirewall firewall show rule name="** TCP Port 1433") -Contains "No rules match the specified criteria.")
{
netsh advfirewall firewall add
rule name="**
TCP Port 1433" dir=in protocol=TCP localport=1433
action=allow
}Edit: This script was corrected following the comment below. Parenthesis were missing around the show rule name check in the if statement.
Hi Howard,
ReplyDeleteThanks for posting this! Unfortunately, your script (as written) will not work the way you intended (at least not in Windows 10).
What I discovered is that while the script works the *first* time, it also works every subsequent time the output of "show rule" will include the Edge Traversal option, which, by default is "no", thus satisfying the conditions of the If statement and creating a duplicate entry.
That said, I was able to get the script to work by updating the -contains parameter to read "specified criteria." i.e. :
if(netsh advfirewall firewall show rule name="** TCP Port 1433" -contains "specified criteria.") {
netsh advfirewall firewall add rule name="** TCP Port 1433" dir=in protocol=TCP localport=1433 action=allow
}
These two words both appear in the show rule output when the rule Doesn't Exist AND NOT when the rule *Does* Exist.
I hope that helps, and thanks again for the post!
Hello,
DeleteThank you for the reply. You are correct that there was an issue with my script. The show rule check was not in parenthesis so it was not valid and always executed the code in the if statement.
This has now been corrected in the original post.