将多个远程地址添加到防火墙规则的 Powershell 脚本 [英] Powershell script to add multiple remote address to firewall rules
问题描述
我正在尝试编写一个脚本,该脚本将遍历本地防火墙规则并更新远程地址表.
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
}
$name 变量传入我想按名称更改的规则,$ips 变量传入我想要的 IP 地址.
The $name variable passes in the rules I want to alter by name, the $ips variable passes in the IP addresses I want.
这个脚本看起来对吗?
更新
在@Kev 的帮助下,由于某种原因,他的评论/答案消失了,这是工作脚本......
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
}
我唯一的另一个问题是,为什么是 $r.DisplayName?
My only other question, is why is it $r.DisplayName?
推荐答案
-RemoteAddress
参数采用字符串数组,因此您应该更改:
The -RemoteAddress
parameter takes a string array, so you should change:
$ips = "192.168.1.150, 192.168.1.151"
到:
$ips = @("192.168.1.150", "192.168.1.151")
更新:
根据您在下面的评论,您不需要将 Get-NetFirewallRule
的结果通过管道传输到 ft
或 Format-Table
.改为这样做:
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.
将 IP 地址添加到规则中的现有 IP 范围:
如果您已经有一个分配了一个或多个 IP 的规则,您可以通过执行以下操作来附加其他 IP:
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
这篇关于将多个远程地址添加到防火墙规则的 Powershell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!