Adding an Application Rule to the Windows Firewall with PowerShell
The script below was adapted from the vbscript code at:
http://msdn.microsoft.com/en-us/library/aa364695(v=VS.85).aspx
#--********************************************************************/
# This PowerShell script includes sample code for adding an Application
# rule using the Microsoft Windows Firewall APIs.
#--********************************************************************/
set-psdebug -strict
$CurrentProfile = $null
# Protocol
set-variable -name NET_FW_IP_PROTOCOL_TCP -value 6 -option constant
# Action
set-variable -name NET_FW_ACTION_ALLOW -value 1 -option constant
# Create the FwPolicy2 object.
$fwPolicy2 = $null
$fwPolicy2 = new-object -comobject HNetCfg.FwPolicy2
# Get the Rules object
$RulesObject = $null
$RulesObject = $fwPolicy2.Rules
$CurrentProfiles = $fwPolicy2.CurrentProfileTypes
# Create a Rule Object.
$NewRule = $null
$NewRule = new-object -comobject HNetCfg.FWRule
$NewRule.Name = "My Application Name"
$NewRule.Description = "Allow my application network traffic"
$NewRule.Applicationname = "%systemDrive%\Program Files\MyApplication.exe"
$NewRule.Protocol = $NET_FW_IP_PROTOCOL_TCP
$NewRule.LocalPorts = 4000
$NewRule.Enabled = $True
$NewRule.Grouping = "@firewallapi.dll,-23255"
$NewRule.Profiles = $CurrentProfiles
$NewRule.Action = $NET_FW_ACTION_ALLOW
# Add a new rule
$RulesObject.Add($NewRule)
Other Languages
This article is also available in the following languages: