我正在尝试创建一个1. 1的PowerShell脚本(目标级别OS 2008 R2)。
我被困在上面列表的第3点。有人能够帮助或可能指导我朝正确的方向发展吗?
当前代码:
$array = @("3050", "300", "8080","7080","5090")
for ($i=0; $i -lt $array.length; $i++) {
$searchPort = "(LocalPort.*" + $array[$i] + ")"
$front = netsh advfirewall firewall show rule dir=in name=all |
Select-String -Pattern ($searchPort) -Context 9,4
Write-Host $front
}
根据我当前的脚本复制结果:
Rule Name: interbase port ---------------------------------------------------------------------- Enabled: Yes Direction: In Profiles: Domain,Private,Public Grouping: LocalIP: Any RemoteIP: Any Protocol: TCP LocalPort: 3050 RemotePort: Any Edge traversal: No Action: Allow Rule Name: MT ---------------------------------------------------------------------- Enabled: Yes Direction: In Profiles: Domain,Private,Public Grouping: LocalIP: Any RemoteIP: Any Protocol: UDP LocalPort: 300 RemotePort: Any Edge traversal: No Action: Allow Rule Name: medtech port ---------------------------------------------------------------------- Enabled: Yes Direction: In Profiles: Domain,Private,Public Grouping: LocalIP: Any RemoteIP: Any Protocol: UDP LocalPort: 300 RemotePort: Any Edge traversal: No Action: Allow
答案 0 :(得分:0)
只需从匹配的前置上下文中提取规则名称即可。由于您可能希望使用前后上下文中的多个元素,因此我建议将Select-String
的输出汇总到ForEach-Object
而不是将其收集到变量中。然后,您可以切换防火墙规则,例如像这样:
$toggle = @{
'yes' = 'no'
'no' = 'yes'
}
netsh ... | Select-String -Pattern $searchPort -Context 9,4 | ForEach-Object {
$rule = $_.Context.PreContext[0] -replace 'rule name:\s*'
$enabled = $_.Context.PreContext[2] -replace 'enabled:\s*'
& netsh advfirewall firewall set rule name="$rule" new enable=$($toggle[$enabled])
}