Search code examples
windowspowershellpowershell-2.0powershell-3.0windows-firewall

Add Windows firewall rule over PowerShell


I'm adding Windows firewall rules over PowerShell by taking objects from 3 arrays and filling $Params to issue a New-NetFirewallRule command. I can't figure out why my first command is failing with error "Incorrect port number"

Code:

$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
}

So everything is working, except when trying to add first 8883,443 object.

When I try command manually it works:

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

Also when I try to add in @Params "LocalPort" = 8883,443 , the rule is added without errors.

Can anybody help me, cos it driving me crazy for two days already.

Thanks in advance!


Solution

  • Parameter -LocalPort of New-NetFirewallRule is declared as an array String[]. So you have to create a nested array when you want to pass multiple ports:

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