Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicated Windows firewall rules (Netsh AdvFirewall firewall)

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?

like image 643
ShaneC Avatar asked Aug 24 '15 14:08

ShaneC


People also ask

What is netsh advfirewall reset?

Method 4: Reset Firewall Settings to Default via Command Prompt. Open the Command Prompt as administrator, and type this command: netsh advfirewall reset. Once pressing Enter, all the firewall settings are now reset to their default values.

What does the command netsh firewall show config do?

Display Windows Firewall settings using command line The following show commands are used to display the current configuration: show allowedprogram - Displays the excepted programs. show config - Displays the local configuration information. show currentprofile - Displays the current profile.

What is netsh Advfirewall set Allprofiles state off?

Open a command prompt in "Run as administrator" mode (or PowerShell) and enter: netsh advfirewall set allprofiles state off. To verify that Windows Firewall for all networks is off, enter: netsh advfirewall show all. The state should indicate off for Domain, Private, and Public profile settings.

Which netsh commands can be used to allow traffic through the Windows Firewall?

We recommend that you use the netsh advfirewall firewall context to control firewall behavior.


2 Answers

Check if rule "myrule" not exists

netsh advfirewall firewall show rule name="myrule" | findstr "no rules"
like image 128
Oleg Avatar answered Oct 08 '22 06:10

Oleg


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"
}
like image 35
ShaneC Avatar answered Oct 08 '22 06:10

ShaneC