Export–Import Windows Firewall Setting using PowerShell

Something I really hate is to do same thing again and again manually … and so I always try to automate that task using scripting … weather it is simple Batch Script … VB Script … Bash .. or my new favorite PowerShell Open-mouthed smile. What I really like about PowerShell is, it exposes whole .NET stack to you and you can do just about anything you can do in any .NET application … but with lot simplicity (should I add … without need to build whole project !)

From past few months I am beginning to get involved in more system preparation tasks for our production and one of the requirement is to configure Windows Firewall to have some rules for our application. And we have to repeat this process on any machine that goes into production. At one point I realized that if you keep doing something repetitively chances are you will make mistake at some point and you will not notice it until you run into some issue and you back trace your steps !!

Then I found that all of these machines have same configuration in them both hardware wise and software wise … and they will also have same firewall exceptions. So it would be nice if I can seamlessly import – export firewall rules from one machine to another machine. Actually this can be done via UI from Windows Firewall with Advance Security (which can be reached by opening up Windows Firewall in control panel and then clicking on “Advanced Settings”). And there you should see two options, Import Policy and Export Policy. And those options does what they say … import / export firewall policy.

Import-Export-GUI

But being lazy to do repetitive tasks many times I thought that it would be nice to simply create a PS script to do that for me ….. so I ended up having a PowerShell script which does exactly same thing as UI just without much hassle (plus great show off for PS skills in office Winking smile… though it is not actually all PS commands). It actually uses Windows utility called “netsh” (aka Network Shell) which does more than just setting up firewall. So in the end my script was sort of looking like this,

CLS
$choice = Read-Host "1.Export Policy 2.Import Policy"
if ($choice -eq 1)
{ netsh advfirewall export "c:\advfirewallpolicy.wfw" }
else
{ netsh advfirewall import "c:\advfirewallpolicy.wfw" }

 

And next time all I had to do was to export standard firewall policy from one machine and import that policy on any production machine with similar configuration …. the great thing is it highly reduces chances of me or anyone making any errors while configuration firewall.

That’s it for now …

It’s Just A Thought … Peace

Gaurang Sign

Leave a Reply

Your email address will not be published. Required fields are marked *