Posted On December 24, 2019

PowerShell: Setting Windows Firewall Rules

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

PowerShell: Script to Send Emails

In the past, a simple email relay script was sufficient to spool internal messages. However,…

PowerShell: Set Application CPU Affinity on Remote and Local Computers

# setProcessNameToCpuNumber.ps1$computerName =$env:computername$processname="Chrome";function getProcessors{ param( $computerName=$env:computername ) [int]$processors = 0; $cpuObject = Get-WmiObject -computername $computerName…

PowerShell: Moving Virtual Machines & Expanding Disk Volumes in Hyper-V & Microsoft Failover Clusters

Sample VM Migation Plan (time window = 3 hours): Pre-emptively resolve disks merging errors prior…