【发布时间】:2021-10-27 09:26:13
【问题描述】:
我计划在 Windows 上删除重复的防火墙规则。我知道有一组像get-netfirewallrule 这样的防火墙cmdlet,但是当我尝试通过防火墙规则来获取像Get-NetFirewallRule -displayname xxx | Get-NetFirewallApplicationFilter 这样的附加信息时,它太慢了。所以我打算使用老派的方式,netsh advfirewall firewall 命令集。
现在我已将netsh advfirewall firewall 的输出解析为对象数组。
$output = netsh advfirewall firewall show rule name=all verbose | Out-String
$output = [regex]::split($output.trim(), "\r?\n\s*\r?\n");
$objects = @(foreach($section in $output) {
$obj = [PSCustomObject]@{}
foreach($line in $($section -split '\r?\n')) {
if($line -match '^\-+$') {
continue
}
$name, $value = $line -split ':\s*', 2
$name = $name -replace " ", ""
$obj | Add-Member -MemberType NoteProperty -Name $name -Value $value
}
$obj
})
但问题是数组中的对象具有不同的属性。例如,这是一个对象:
RuleName : HNS Container Networking - ICS DNS (TCP-In) - B15BF139-F18D-471C-A18C-92DFD33350F1 - 0
Description : HNS Container Networking - ICS DNS (TCP-In) - B15BF139-F18D-471C-A18C-92DFD33350F1 - 0
Enabled : Yes
Direction : In
Profiles : Domain,Private,Public
Grouping :
LocalIP : Any
RemoteIP : Any
Protocol : TCP
LocalPort : 53
RemotePort : Any
Edgetraversal : No
Program : C:\WINDOWS\system32\svchost.exe
Service : sharedaccess
InterfaceTypes : Any
Security : NotRequired
Rulesource : Local Setting
Action : Allow
这是另一个:
RuleName : HNS Container Networking - DNS (UDP-In) - 91EC1DEF-8CB8-4C2A-A6D4-91480448AE97 - 0
Description : HNS Container Networking - DNS (UDP-In) - 91EC1DEF-8CB8-4C2A-A6D4-91480448AE97 - 0
Enabled : Yes
Direction : In
Profiles : Domain,Private,Public
Grouping :
LocalIP : Any
RemoteIP : Any
Protocol : UDP
LocalPort : 53
RemotePort : Any
Edgetraversal : No
InterfaceTypes : Any
Security : NotRequired
Rulesource : Local Setting
Action : Allow
如您所见,第一个规则使用端口以及定义规则的程序,第二个仅使用端口。如何对对象进行分组并查找重复项(以便我可以删除相应的防火墙规则)?我不能简单地使用$objects | Group-Object -Property rulename,enabled,.....,因为并非所有对象的属性都相同。
顺便说一句,重复的防火墙规则是由我过去编写的一些不完善的脚本创建的。
【问题讨论】:
标签: arrays powershell duplicates grouping firewall