在Powershell中删除和应用防火墙规则非常缓慢

时间:2019-12-19 03:38:28

标签: powershell windows-firewall

我有几个包含New-NetFirewallRule Commandlet的脚本,总共大约有200条规则,要删除现有规则然后应用新规则,大约需要15分钟。

根据文档New-NetFirewallRule,cmdlet具有GPOSession参数,可用于指定GPO对象,使用Open-NetGPO加载GPO,进行修改,然后将GPO重新保存。

但是它是无用的参数,因为它看起来仅适用于域,我在Windows 10单计算机网络上,没有域。

很明显,每个New-NetFirewallRule cmdlet都是针对本地GPO单独调用的,这太慢了,是否有办法以某种方式加载本地组策略,执行所需的操作,然后又将更改应用回去而无需访问每个GPO防火墙规则?

编辑: 为了回应评论,我认为所有规则都很简单,即不处理繁重的呼叫,例如:(有200多个此类规则)

New-NetFirewallRule -Confirm:$Execute -Whatif:$Debug -ErrorAction $OnError -Platform $Platform `
-DisplayName "Multicast Domain Name System" -Service Dnscache -Program $ServiceHost `
-PolicyStore $PolicyStore -Enabled True -Action Allow -Group $Group -Profile Private, Domain -InterfaceType $Interface `
-Direction $Direction -Protocol UDP -LocalAddress Any -RemoteAddress 224.0.0.251 -LocalPort 5353 -RemotePort 5353 `
-LocalUser Any -LocalOnlyMapping $false -LooseSourceMapping $false `
-Description "In computer networking, the multicast DNS (mDNS) protocol resolves hostnames to IP addresses
within small networks that do not include a local name server."

许多变量是预定义的,但是只有少数几个变量使用更复杂的调用,但这仅在脚本初始化期间发生一次。

例如找出回送接口别名:

$Loopback = Get-NetIPInterface | Where-Object {$_.InterfaceAlias -like "*Loopback*" -and $_.AddressFamily -eq "IPv4"} | Select-Object -ExpandProperty InterfaceAlias

要删除规则,我使用以下命令,该命令将删除一组规则:

Remove-NetFirewallRule -PolicyStore $PolicyStore -Group $Group -Direction $Direction -ErrorAction SilentlyContinue

1 个答案:

答案 0 :(得分:1)

您可以使用本地安全策略工具(secpol.msc)进行配置并将其导出到.inf文件中。然后在目标计算机上,使用相同的工具导入.infsecedit.exe进行脚本编写:(如果导出的文件是mypolicy.inf

secedit /configure /db %windir%\security\local.sdb /cfg mypolicy.inf