Working with firewall rules

Needed to be able to work with firewall rules on servers at work, so decided to start by getting the actual rule query and update part done, so I can add them to a more fleshed out script later.

#NetFirewallRule method for newer versions of Powershell

#Create a new test rule
New-NetFirewallRule -DisplayName "BLACKLIST_IN" -RemoteAddress 9.9.9.9 -Direction Inbound -Protocol TCP -LocalPort Any -Action Block

#Get the IP addresses in the current rule for the remote address field
$curIP = (Get-NetFirewallRule -DisplayName "BLACKLIST_IN" | Get-NetFirewallAddressFilter).RemoteAddress

#Define the new IP addresses to add, and then merge the lists
$newIPs = "9.9.9.10-9.9.9.11","9.9.9.14/31"
$addIPs = @($newIPs) + @($curIP)

#Set the rule with the new list
Set-NetFirewallRule -DisplayName "BLACKLIST_IN" -RemoteAddress $addIPs
Code language: PowerShell (powershell)
#netsh version for older versions of Powershell

#Get the current rule and convert it from comma separated to a list
$netshout = netsh advfirewall firewall show rule name="BLACKLIST_IN"
$nshIP=($netshout | findstr RemoteIP).trim("RemoteIP: ").split(",")

#Define the new IP addresses to add, and then merge the lists
$newnshIPs = "9.9.9.13","9.9.9.14/31"
$nshaddIPs = @($nshIP) + @($newnshIPs)

#Take the new list and convert back to comma separated
$IPList = ($nshaddIPs | Select-Object) -join ","

#Set the rule with the new list
netsh advfirewall firewall set rule name ="BLACKLIST_IN" new remoteip=$IPList
Code language: PowerShell (powershell)

Leave a Comment

nine − three =