Powershell从Windows防火墙规则作用域中删除IP



我有一个windows防火墙阻止规则,其中Ip由PowerShell脚本自动添加,该脚本通过基于事件的计划任务触发。

我想创建另一个PowerShell脚本,它将查询防火墙阻止规则,从那里获取远程地址,并删除我通过变量传递的地址。

$Whitelist = 1.2.3.4
#Get firewall object
$fw = New-Object -ComObject hnetcfg.fwpolicy2
#Get firewall rule named 'test' (must be created manually)
$ar = $fw.rules | where {$_.name -eq 'test'}
#Split the existing IPs into an array so we can search it for existing IPs
$arRemote = $ar.RemoteAddresses -split(',')
#Remove Ip from remote addresses
$w = (Need Help Here)
#Add the new IPs to firewall rule
$w| %{
if ($ar.RemoteAddresses -eq '*') {
$ar.remoteaddresses = $_.Name
}else{
$ar.remoteaddresses += ',' + $_.Name
}
}

如果我理解正确,您可以简单地使用Where-Object子句来过滤$WhiteList中的任何IP,如下所示:

# set up the whitelist as array of strings
$Whitelist = '1.2.3.4', '10.10.2.1'
# filter all ips to block that are not found in the $Whitelist
$blockedIps = $ar.RemoteAddresses -split ',' | Where-Object { $whitelist -notcontains $_ }
# join the resulting ips with a comma and repopulate the RemoteAddresses property
$ar.RemoteAddresses = $blockedIps -join ','

最新更新