PowerShell: Setting Windows Firewall Rules

# Set variables for HTTP
$protocolName="HTTP"
$protocol="TCP"
$portNumbers='80','443'
$direction="Inbound"
$scopes='Domain', 'Private'

# Add Firewall Rule
New-NetFirewallRule -DisplayName "$protocolName-$direction" -Profile @($scopes) -Direction $direction -Action Allow -Protocol $protocol -LocalPort @($portNumbers)

# Set variables for VNC
$protocolName="VNC"
$protocol="TCP"
$portNumbers='5900'
$direction="Inbound"
$scopes='Domain', 'Private'

# Add Firewall Rule
New-NetFirewallRule -DisplayName "$protocolName-$direction" -Profile @($scopes) -Direction $direction -Action Allow -Protocol $protocol -LocalPort @($portNumbers)

<# Errors on Windows with PowerShell versions less than 3.0
The term 'New-NetFirewallRule' is not recognized as the name of a cmdlet, function, script file, or operable program. C
heck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:20
+ New-NetFirewallRule <<<< -DisplayName "$protocolName-$direction" -Profile @($scopes) -Direction $direction -Action A
llow -Protocol $protocol -LocalPort @($portNumbers)
+ CategoryInfo : ObjectNotFound: (New-NetFirewallRule:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
#>

$portNumbers|%{netsh advfirewall firewall add rule name='$protocolName-$direction-$_' dir=in action=allow protocol=$protocol localport=$_;}

Leave a Reply

Your email address will not be published. Required fields are marked *