简体   繁体   English

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

[英]Powershell to Remove an IP from a Windows Firewall rule scope

I have a windows firewall Block rule where Ip's are getting added automatically by a PowerShell script triggered through a scheduled task based on an event.我有一个 Windows 防火墙阻止规则,其中 Ip 由基于事件的计划任务触发的 PowerShell 脚本自动添加。

I'm looking to create another PowerShell script which will query that firewall block rule gets the Remote addresses from there and remove the one which I pass through a variable.我正在寻找创建另一个 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
      }
    }

If I understand correctly, you can simply use a Where-Object clause to filter out any IP that is in $WhiteList like this:如果我理解正确,您可以简单地使用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 ','

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM