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
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.
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.
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"}
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