通过 PowerShell 添加 Windows 防火墙规则

问题描述

我通过从 3 个数组中获取对象并填充 $Params 以发出 New-NetFirewallRule 命令,在 PowerShell 上添加 Windows 防火墙规则。我不明白为什么我的第一个命令失败并显示错误“端口号不正确”

代码

$All = @( '13.79.172.43','13.69.228.5','1.1.1.1' )
$AllPorts = @( '8883,443','443','80' )
$AllProtocols = @( 'TCP','TCP','TCP' )

for ($i = 0; $i -lt $All.Count; $i++) {

    $Params = @{ 
        "displayName" = '"Block-WiFi-' + $i  
        "Name" = 'Block-WiFi-' + $i 
        "Direction" = 'Inbound' 
        "InterfaceType" = 'Wireless'
        "Action" = 'Block'
        "RemoteAddress" = $All[$i]
        "LocalPort" = $AllPorts[$i]
        "Protocol" = $AllProtocols[$i]
    }

    # Add Windows Firewall RUle
    New-NetFirewallRule @Params

    # Check what is going on
    Write-Host "Address: $($All[$i])  |  Port: $($AllPorts[$i])   |   Protocol: $($AllProtocols[$i])"    
    Write-Host "----------------------------------------------------------------------------------"
    Start-Sleep 2
}

所以一切正常,除非尝试添加一个 8883,443 对象。

当我手动尝试命令时,它可以工作:

New-NetFirewallRule -displayName "Block-Wireless-In-01" -Name "Block-Wireless-In-01" -Direction Inbound -InterfaceType Wireless -Action Block -RemoteAddress 13.79.172.43 -LocalPort 8883,443 -Protocol TCP

此外,当我尝试添加 @Params "LocalPort" = 8883,443 时,添加的规则没有错误

谁能帮助我,因为它已经让我发疯了两天。

提前致谢!

解决方法

Parameter -LocalPort of New-NetFirewallRule 被声明为数组 String[]。所以当你想传递多个端口时,你必须创建一个嵌套数组:

$AllPorts = @( @('8883','443'),'443','80' )