Using Group Policy in Active Directory, you can force the Windows Firewall to be enabled across your servers or clients, but sometimes you might not want to do that.  After all, when troubleshooting a software communications problem, it’s really easy to rule out the firewall configuration as a possible problem if you can disable it for a few minutes while you troubleshoot.

The only problem with allowing that kind of flexibility is how do you know that you remembered to re-enable the firewall on those 30 servers you worked on last week?  Well, some quick googling will show that you can use WMI to query the HNet_ConnectionProperties class and look at the IsFirewalled property.  Except….it’s always True!  Even if the firewall is disabled.  Apparently, this is because the ICS service is running so the property is a bit misleading.

So I did things the hard way.  I used Regmon to find out what registry key was flipped on/off when I enabled/disabled the Windows Firewall, and wrote a quick Powershell function to query that setting and return True or False (as type [bool]).

# returns true if windows firewall is enabled, false if it is disabled
filter global:get-firewallstatus ([string]$computer = $env:computername)
	if ($_) { $computer = $_ }

	$HKLM = 2147483650

	$reg = get-wmiobject -list -namespace root\default -computer $computer | where-object { $ -eq "StdRegProv" }
	$firewallEnabled = $reg.GetDwordValue($HKLM, "System\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy\DomainProfile","EnableFirewall")


Update (Feb 1, 2009):

In the comments, Shay Levy reminded me of an alternate method of querying the registry that doesn’t use WMI. Here is the exact same script using the [Microsoft.Win32.RegistryKey] class. Thanks Shay!

filter global:get-firewallstatus2 ([string]$computer = $env:computername)
	if ($_) { $computer = $_ }

	$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$computer)

	$firewallEnabled = $reg.OpenSubKey("System\ControlSet001\Services\SharedAccess\Parameters\FirewallPolicy\DomainProfile").GetValue("EnableFirewall")