How can I add a Windows firewall rule with a custom group name?
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
The following Powershell one-liner adds/renames Group name for the rules with DisplayName='GTA V'. Works for Windows 8+
Get-NetFirewallRule -DisplayName 'GTA V' | ForEach { $_.Group = 'games'; Set-NetFirewallRule -InputObject $_ }