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?
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.
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.
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.
We recommend that you use the netsh advfirewall firewall context to control firewall behavior.
Check if rule "myrule" not exists
netsh advfirewall firewall show rule name="myrule" | findstr "no rules"
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With