如何 Disable/Enable Windows 基于关联端口号的防火墙规则

How to Disable/Enable Windows Firewall Rule based on associated port number

我正在尝试创建一个 PowerShell 脚本(目标级别 OS 2008 R2)1.

  1. 运行s 通过一组端口
  2. 列出与端口关联的所有防火墙策略
  3. 将"Rule Names"捕获到一个数组中当前卡在此处
  4. 运行 通过每个 "Rule Name",根据当前状态禁用或启用策略。

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

只需从匹配的前置上下文中提取规则名称。由于您可能想要使用前上下文和 post 上下文中的多个元素,我建议将 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])
}