locked
Powershell script to check for existance of rule in Firewall RRS feed

  • Question

  • 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?

    • Moved by Dave PatrickMVP Tuesday, December 8, 2020 2:45 PM looking for forum
    Tuesday, December 8, 2020 2:44 PM

Answers

  • I'd try asking for help over here.

    windows-server-powershell - Microsoft Q&A

     

     



    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows Server] Datacenter Management

    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees, and confers no rights.

    • Proposed as answer by Guido Franzke Wednesday, December 9, 2020 7:03 AM
    • Marked as answer by Guido Franzke Wednesday, December 16, 2020 7:03 AM
    Tuesday, December 8, 2020 2:45 PM