Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you check for existing firewall rules using Powershell

So, I've got this script:

function Add-FirewallRule {
   param( 
      $name,
      $tcpPorts,
      $appName = $null,
      $serviceName = $null
   )
    $fw = New-Object -ComObject hnetcfg.fwpolicy2 
    $rule = New-Object -ComObject HNetCfg.FWRule

    $rule.Name = $name
    if ($appName -ne $null) { $rule.ApplicationName = $appName }
    if ($serviceName -ne $null) { $rule.serviceName = $serviceName }
    $rule.Protocol = 6 #NET_FW_IP_PROTOCOL_TCP
    $rule.LocalPorts = $tcpPorts
    $rule.Enabled = $true
    $rule.Grouping = "@firewallapi.dll,-23255"
    $rule.Profiles = 7 # all
    $rule.Action = 1 # NET_FW_ACTION_ALLOW
    $rule.EdgeTraversal = $false
    if(*here*)
    {
    $fw.Rules.Add($rule)
    }

}

and I want to be able to put something in the if() that will check and see if the rule already exists before it adds it. I'm not terribly familiar with powershell, so go easy on me :P

like image 648
tjernigan Avatar asked Jul 06 '11 14:07

tjernigan


People also ask

How do I check firewall settings in powershell?

To get the setting using GUI, you need to search in the box Windows Firewall with Advanced Security or Windows Defender Firewall with Advanced Security. Then you can see in the console that 3 available profiles. The above same settings can be viewed with the PowerShell Get-NetFirewallProfile command.

How do I check my firewall inbound rules?

Answer: From the Control Panel, navigate to System and Security, and click on Windows Firewall. Go to the Advanced settings and right-click on Inbound Rules on the left pane.


1 Answers

PowerShell Firewall example for SDL Microservices

Only create a new firewall rule if it does not already exist

$rules = Get-NetFirewallRule

$par = @{
    DisplayName = ""
    LocalPort = 80
    Direction="Inbound"
    Protocol ="TCP" 
    Action = "Allow"
}

$par.LocalPort = 8081
$par.DisplayName = "SDL Web 8 Stage Content Microservice on port $($par.LocalPort)"
if (-not $rules.DisplayName.Contains($par.DisplayName)) {New-NetFirewallRule @par}

$par.LocalPort = 8082
$par.DisplayName = "SDL Web 8 Stage Discovery Microservice on port $($par.LocalPort)"
if (-not $rules.DisplayName.Contains($par.DisplayName)) {New-NetFirewallRule @par"}
like image 66
Chris Mills Avatar answered Nov 15 '22 07:11

Chris Mills