I have several scripts containing New-NetFirewallRule
commandlets, in total there are about 200 rules, and to delete existing rules and then apply new ones it takes about 15 minutes.
According to documentation New-NetFirewallRule
cmdlet has GPOSession
paramter which lets you specify GPO object, the GPO is loaded using Open-NetGPO
, you do modifications and then save the GPO back.
However it's useless parameter since it looks like this only works for domains, I'm on Windows 10 single computer network, no domain.
Obviously each New-NetFirewallRule
cmdlet is called independently against localhost GPO, which is too slow, is there a way to load local group policy somehow, do what you want, and then apply changes back without accessing the GPO for each firewall rule?
EDIT: To respond on comment I think all the rules are simple enough, ie. not dealing with heavy calls, like this: (there are 200+ such rules)
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."
A lot of variables are predefined, but only a few variables use more complex call but this happens only once during initialization of a script.
for example to figure out loopback interface alias:
$Loopback = Get-NetIPInterface | Where-Object {$_.InterfaceAlias -like "*Loopback*" -and $_.AddressFamily -eq "IPv4"} | Select-Object -ExpandProperty InterfaceAlias
To delete rules, I use this command, which deletes a group of rules:
Remove-NetFirewallRule -PolicyStore $PolicyStore -Group $Group -Direction $Direction -ErrorAction SilentlyContinue
You could user Local Security Policy tool (secpol.msc
) to make your configuration and export it to an .inf
file. Then on the target machine either use the same tool to import the .inf
or secedit.exe
for scripting: (if the file exported was mypolicy.inf
)
secedit /configure /db %windir%\security\local.sdb /cfg mypolicy.inf