Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

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!

question from:https://stackoverflow.com/questions/65842236/add-windows-firewall-rule-over-powershell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...