Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell script to add multiple remote address to firewall rules

Tags:

powershell

I am trying to write a script that will loop through local firewall rules and update the remote address table.

Here is what I have so far, it does not work. Should be simple, so not sure whats going on. The script runs without error, but does not actually update anything.

$name = Get-NetFirewallRule -DisplayName "*Desktop*" |ft   -HideTableHeaders Displayname
$ips = "192.168.1.150, 192.168.1.151"
foreach ($r in $name)
{
Set-NetFirewallRule -DisplayName $r -RemoteAddress $ips 
}

The $name variable passes in the rules I want to alter by name, the $ips variable passes in the IP addresses I want.

Does this script look right?

Updated

With the help of @Kev, whose comments/answers dissappeared for some reason, this is the working script....

$name = Get-NetFirewallRule -DisplayName "*Backup*" 
#$ips = @("192.168.1.150", "192.168.1.151")
foreach ($r in $name)
{
Set-NetFirewallRule -DisplayName $r.DisplayName -RemoteAddress $ips 
}

My only other question, is why is it $r.DisplayName?

like image 646
Nov2009 Avatar asked Feb 12 '16 16:02

Nov2009


People also ask

What is NetFirewallRule?

Description. The New-NetFirewallRule cmdlet creates an inbound or outbound firewall rule and adds the rule to the target computer. Some parameters are used to specify the conditions that must be matched for the rule to apply, such as the LocalAddress and RemoteAddress parameters.

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.


1 Answers

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
like image 54
Kev Avatar answered Sep 18 '22 05:09

Kev