How can I add a Windows firewall rule with a custom group name?

Achilles picture Achilles · Aug 14, 2012 · Viewed 9k times · Source

I know I can use netsh advfirewall firewall add rule or wf.msc to create new firewall rules; but when I create a rule this way, it will NOT have a groupName and thus I can't manage multiple rules at the same time.

Is there a way to specify a groupName for some firewall rules?

Answer

Achilles picture Achilles · Aug 14, 2012

OK! I know how I should do it now :)
Using PowerShell and WMI COM-Objects I can do what I want!
This is a ps1 script I wrote to add firewall rules so that I can connect to my SQL Server remotely.

function isFirewallPortOpen {
    param( [int] $port )
    $fw = New-Object -ComObject hnetcfg.fwpolicy2 
    if ($fw.Rules | Where {$_.LocalPorts -eq $port }) {
        return [bool]$true
    } else {
        return [bool]$false
    }
}

function existsFirewallRule {
    param( [string] $name )
    $fw = New-Object -ComObject hnetcfg.fwpolicy2 
    if ($fw.Rules | Where { $_.Name -eq $name }) {
        return [bool]$true
    } else {
        return [bool]$false
    }
}

function addFirewallRule {
    param(
        [string] $name,
        [int] $port,
        [int] $protocol
    )
    $fw = New-Object -ComObject hnetcfg.fwpolicy2 
    if (isFirewallPortOpen $port -or existsFirewallRule $name) {
        Write-Host -ForegroundColor:Red "**Rule Already Exists or Port Already Open."
    } else {
        $rule = New-Object -ComObject HNetCfg.FWRule

        $rule.Name = $name
        $rule.Protocol = $protocol # 6=NET_FW_IP_PROTOCOL_TCP and 17=NET_FW_IP_PROTOCOL_UDP
        $rule.LocalPorts = $port
        $rule.Enabled = $true
        $rule.Grouping = "SQL Server"
        $rule.Profiles = 7 # all
        $rule.Action = 1 # NET_FW_ACTION_ALLOW
        $rule.EdgeTraversal = $false

        $fw.Rules.Add($rule)
        Write-Host -ForegroundColor:Blue "A rule named '$name' has been added to Windows' Firewall."
    }
}

addFirewallRule -name:"Transact SQL Debugger" -port:135 -protocol:6
addFirewallRule -name:"SQL Traffic" -port:1433 -protocol:6
addFirewallRule -name:"SQL Browser Traffic" -port:1434 -protocol:17
addFirewallRule -name:"SQL Analytics Traffic" -port:2383 -protocol:6
addFirewallRule -name:"SQL Broker Traffic" -port:4022 -protocol:6