Freigeben über


Adding a Windows Firewall rule using PowerShell

PowerShell is an amazing technology which I’d love to learn to use properly some day. Unfortunately I’m still at the stage where I don’t really know much about it, but from time to time I need to use it to solve random problems. Luckily, trial and error is a great way of slowly increasing one’s understanding.

The problem I needed to solve today was to add new Windows Firewall rules. I found a few posts (like this and this) showing how to do a few things with Firewall rules, but not add new rules. There are also some good VBScript samples on MSDN  which I used as a starting point.

Here’s my simple generic function to add a new firewall rule. I’ve hard-coded many of the values based on my needs, but you should be able to modify the script pretty easily if you need to create different kinds of rules. Feel free to ridicule me if I’ve done anything to indicate my PowerShell novice status.

 function Add-FirewallRule {
   param( 
      $name,
      $tcpPorts,
      $appName = $null,
      $serviceName = $null
   )
    $fw = New-Object -ComObject hnetcfg.fwpolicy2 
    $rule = New-Object -ComObject HNetCfg.FWRule
        
    $rule.Name = $name
    if ($appName -ne $null) { $rule.ApplicationName = $appName }
    if ($serviceName -ne $null) { $rule.serviceName = $serviceName }
    $rule.Protocol = 6 #NET_FW_IP_PROTOCOL_TCP
    $rule.LocalPorts = $tcpPorts
    $rule.Enabled = $true
    $rule.Grouping = "@firewallapi.dll,-23255"
    $rule.Profiles = 7 # all
    $rule.Action = 1 # NET_FW_ACTION_ALLOW
    $rule.EdgeTraversal = $false
    
    $fw.Rules.Add($rule)
}
 # Sample Usage
Add-FirewallRule "Test port 1234" "1234" $null $null
Add-FirewallRule "Test port 5555-6666" "5555-6666" $null $null
Add-FirewallRule "Test port 2222 Calc" 2222 "c:\windows\system32\calc.exe" $null
Add-FirewallRule "Test port 3333 W3SVC" 3333 $null "W3SVC"

Comments

  • Anonymous
    November 07, 2010
    Thanks for sharing, Tom!