parsing netsh firewall using powershell

In this powershell treasure chest post I want to explain how we can parse the results of netsh advfirewall command to workable powershell objects using regex. For the ones that didn’t know, netsh advfirewall is a command that allows to lists the existing firewall rules and their state on a windows machine. It has been pretty handy up until the *netadvancedFirewall* cmdlets were released.

This blog post answers the question: How do can I get the firewall rules from a machine using windows PowerShell?

Why not use the standard get-netadvancedFirewall you may ask? Well, how do you get the existing firewall rules from a system ? Normally we would use the get-netadvancedFirewall rule. But even though it is documented that the cmdlet only exists since powershell 3, this is partially false. The powershell firewall cmdlets are available since windows 2012 and windows 8.1 only. This means that even though you have powershell 3.0 installed on anterior version of Windows Server 2012, you won’t have access to powershell cmdlets. Bummer!

But how can you read the existing firewall rules on an system that hasn’t windows Powershell 3.0 then? We know we can have a listing of all the existing rules using netsh with the following example.

If you want to get a specific firewall rule using netsh you can get it using the command as followed:

The results that we get are not objects. It is plain text (buuu!!). But they seem to follow a pattern. Which means, that they are ‘regexable’ 😉

In the absence of the Get-NetAdvancedFirewall, it is possible to get the current firewall rules using netsh adfirewall. The issue is that netsh return only plain text.. o/

If you follow my blog, you must have seen my post about regex, where I teach the basics building blocks to start using regex. the function I am sharing here under is based on the knowledge from that blog post. It is defenitly a good idea to learn regex because it will REALLY help you in the future. Belive me!

This function is based on regular expressions, and it’s sole purpose was for me to get access to the PowerShell remoting firewall rules on servers that didn’t had the net module installed / or available.

Here a quick overview of the objects that are sent back from the function.

Get-netshfirewallrule

I have uploaded the function to github. I would love to have your feedback on this function 🙂

.gist table { margin-bottom: 0; }

#Stéphane