Powershell script to add multiple remote address to firewall rules

in case you need to remove duplicate items and also sort the ips you can do this

$newips =@("1.2.3.4","5.3.4.5","4.2.3.5")
$ips  = (Get-NetFirewallRule -DisplayName "Block Attacker" | Get-NetFirewallAddressFilter ).RemoteAddress
$ipconcat = $ips + $newips
$ipconcat = $ipconcat | select -Unique | sort
Set-NetFirewallRule -DisplayName "Block Attacker" -RemoteAddress $ipconcat

Combining the above answers, this is what I ended up using - this ADDS an ARRAY of IPs to the existing IPs in the rule:

$ips = (Get-NetFirewallRule -DisplayName "MyRule" | Get-NetFirewallAddressFilter ).RemoteAddress
$newips = @("1.1.1.1","2.2.2.2")
$add = $ips + $newips
Set-NetFirewallRule -DisplayName "My Rule" -RemoteAddress $add

The -RemoteAddress parameter takes a string array, so you should change:

$ips = "192.168.1.150, 192.168.1.151"

to:

$ips = @("192.168.1.150", "192.168.1.151")

Updated:

Per your comment below, you don't need to pipe the result of Get-NetFirewallRule into ft or Format-Table. Do this instead:

$name = Get-NetFirewallrule -DisplayName "*Desktop*"

$ips = @("1.1.1.1", "2.2.2.2")

foreach($r in $name)
{
    Set-NetFirewallRule -DisplayName $r.DisplayName -RemoteAddress $ips
}

What you're doing is iterating the array of firewall objects directly which is slightly more efficient.

Adding an IP address to an existing range of IPs in a rule:

If you already have a rule which has been assigned one or more IP's, you can append additional IP's by doing:

$ips = (Get-NetFirewallRule -DisplayName "MyRule" | Get-NetFirewallAddressFilter ).RemoteAddress
$ips += "192.168.1.123"
Set-NetFirewallRule -DisplayName "MyRule" -RemoteAddress $ips

Tags:

Powershell