question

TomaszZarzycki-7215 avatar image
0 Votes"
TomaszZarzycki-7215 asked TomaszZarzycki-7215 commented

How to check if rule in firewall exists. If so stop script and not add new rule, if not then apply new rule in Powershell

Hi,

I am looking for a solution to check if rule in firewall exists. If so stop script and not add new rule, if not then apply new rule.

This rule is for ICMPv4 protocol and so far I have made this way:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted
$firewallProtocol = "ICMPv4"
$firewallRuleName = "All ICMPv4"

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

When applying this I have result:

Checking for 'All ICMPv4' firewall rule with protocol 'ICMPv4' now....
Firewall rule for 'All ICMPv4' with 'ICMPv4' Protocol does not already exist, creating new rule now...
The following command was not found: New-NetFirewallRule -DisplayName "All ICMPv4" -Direction Inbound -Profile Domain,Private,Public -Action Allow -Protocol ICMPv4 -RemoteAddress Any.
Firewall rule for 'All ICMPv4' with 'ICMPv4' Protocol created successfully

Any solutions for this?

windows-server-powershell
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The script looks fine but the error in result doesn't look like a normal powershell error message to me. How did you run the script?

0 Votes 0 ·

It was in unlockping.ps1 file which was triggered on admin rights from powershell ISE.

0 Votes 0 ·

0 Answers