如何使用Powershell检查现有的防火墙规则 [英] How can you check for existing firewall rules using Powershell

查看:552
本文介绍了如何使用Powershell检查现有的防火墙规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有这个脚本:

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
    if(*here*)
    {
    $fw.Rules.Add($rule)
    }

}

,我希望能够在if()中放入一些内容,以检查规则添加之前是否已经存在.我对Powershell并不十分熟悉,所以对我轻松一点:P

and I want to be able to put something in the if() that will check and see if the rule already exists before it adds it. I'm not terribly familiar with powershell, so go easy on me :P

推荐答案

MSDN在此处提供了有关Windows防火墙API的大量文档:

MSDN has some extensive documentation on the Windows Firewall API here:

http://msdn.microsoft.com /en-us/library/aa366449(v=vs.85).aspx

您首先要实例化HNetCfg.FwMgr COM对象-这将使您可以通过HNetCfg.FwMgr.LocalPolicy.CurrentProfile查询各种现有规则.

You'll want to start with instantiating the HNetCfg.FwMgr COM object -- this will give you access to query various existing rules via the HNetCfg.FwMgr.LocalPolicy.CurrentProfile.

有几种不同类型的规则:授权的应用程序,全局打开的端口,ICMP设置和服务". INetFwProfile对象(通过CurrentProfile检索)具有允许访问这些规则的属性.

There are several different types of rules: Authorized Applications, Globally Open Ports, ICMP settings, and "services." The INetFwProfile object (retrieved via the CurrentProfile) has properties that allow access to these rules.

http://msdn.microsoft.com /en-us/library/aa365327(v=vs.85).aspx

更新(2014-01-30):在Windows 8和Windows Server 2012中,有一个名为NetSecurity的PowerShell模块,其中包含Get-NetFirewallRule命令.您可以使用此命令来发现已经定义了哪些防火墙规则.要添加新的防火墙规则,请在同一NetSecurity模块中使用New-NetFirewallRule命令.

Update (2014-01-30): In Windows 8 and Windows Server 2012, there is a PowerShell module called NetSecurity, which contains the Get-NetFirewallRule command. You can use this command to discover which firewall rules are already defined. To add a new firewall rule, use the New-NetFirewallRule command in the same NetSecurity module.

这篇关于如何使用Powershell检查现有的防火墙规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆