通过 PowerShell 添加 Windows 防火墙规则

Add Windows firewall rule over PowerShell

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

代码:

$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' )