如何使用自定义组名添加Windows防火墙规则?

时间:2012-08-14 16:00:03

标签: windows-firewall windows-networking

我知道我可以使用netsh advfirewall firewall add rulewf.msc来创建新的防火墙规则;但是当我以这种方式创建规则时,它将没有 groupName ,因此我无法同时管理多个规则。

有没有办法为某些防火墙规则指定 groupName

4 个答案:

答案 0 :(得分:3)

OK!我知道我现在应该怎么做:) 使用PowerShellWMI COM-Objects我可以做我想做的事! 这是我写的一个ps1脚本,用于添加防火墙规则,以便我可以远程连接到SQL Server

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

答案 1 :(得分:3)

以下Powershell单行为DisplayName =' GTA V'添加/重命名规则的组名。适用于Windows 8 +

Get-NetFirewallRule -DisplayName 'GTA V' | ForEach { $_.Group = 'games'; Set-NetFirewallRule -InputObject $_ }

答案 2 :(得分:1)

$fw= New-Object -ComObject hnetcfg.fwpolicy2
$fw.rules | ? {$_.name -like "*sql*"} | ft name,grouping
$fw.rules | ? {$_.name -like "*sql*"} | % {$gn="_mssqlservices";$_.grouping = $gn}
$fw.rules | ? {$_.name -like "*sql*"} | ft name,grouping

答案 3 :(得分:0)

$rule = Get-NetFirewallRule -Name 'nameme'; $rule.Group = 'nameme'; $rule | Set-NetFirewallRule; 
netsh advfirewall firewall show rule name=nameme
netsh advfirewall set allprofiles state on
netsh advfirewall set allgroups on
netsh advfirewall firewall add rule name="nameme" dir=out action=Allow
netsh advfirewall export "C:\temp\WFconfiguration.wfw"
netsh advfirewall import "C:\temp\WFconfiguration.wfw"

注意:您必须首先在Windows防火墙中创建规则名称,然后将nameme更改为运行Power Shell管理员的名称。

对于组名=任何

enter image

管理Windows防火墙现在比以往更加轻松只需下载