2016-10-01 97 views
0

我想創建一個PowerShell腳本(目標水平OS 2008 R2),其1根據相關的端口號

  1. 貫穿一個陣列孔
  2. 名單如何禁用/啓用Windows防火牆規則通過每個「規則名稱」,禁用或啓用基於當前狀態下的政策與港口
  3. 捕獲「規則名稱」關聯到一個數組目前困在這裏
  4. 運行所有的防火牆策略。

我被困在我上面列表的第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

只要從比賽的預定上下文中提取規則名稱。由於您可能想要使用前後環境中的多個元素,因此建議將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]) 
} 
+0

是=否和否=是 –

+0

非常感謝您的確切需求!如果在QT中,NZ我欠你一杯啤酒! –

+1

嗨, 只是加入快速注意到我發現切換沒有直通到「使能」所以我做了哪去了這樣一個新的變量: \t的netsh ... | Select-String -Pattern $ searchPort -Context 9,4 | ForEach-Object {rule = $ _。Context.PreContext [0] -replace'rule name:\ s *' \t \t $ enabled = $ _。Context.PreContext [2] -replace'enabled:\ S *」 \t \t $ NEWSTATUS = $撥動[$]有效 \t \t及的netsh advfirewall防火牆設置規則名稱= 「$規則」 新啓用= 「$ NEWSTATUS」 \t}再次 –