Powershell从Windows防火墙规则范围中删除IP

时间:2020-08-26 12:08:54

标签: powershell security windows-server-2016 windows-firewall

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

我正在寻找另一个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
      }
    }

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以简单地使用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 ','