Powershell – Windows firewall rules with ports

Every couple of months, I need to check Windows firewall on some secure/crucial Windows servers. I needed a automatic report that I can go through quickly. I used powershell, which goes through firewall rules, and in the end it creates an simple HTML report. Parts of code were used from Spiceworks Community

$ExportReport = "C:\Temp"
$Rules=(New-object -ComObject HNetCfg.FWPolicy2).rules|Where-Object {$_.enabled} |Sort-Object -Property direction,name |foreach-object{ [PSCustomObject] @{
FWName = $_.name
FWDescription= $_.description
FWApplicationName = $_.ApplicationName
FWServiceName = $_.ServiceName
FWProtocol = switch($_.Protocol)  { #https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
                                    256 {'Any'}
                                    58 {'IPv6-ICMP'}
                                    41 {'IPv6'}
                                    17 {'UDP'}
                                    6 {'TCP'}
                                    2 {'IGMP'}
                                    1 {'ICMP'}
                                    default {$_.Protocol}
                                    }
FWLocalPorts = $_.LocalPorts
FWRemotePorts =  $_.RemotePorts
FWLocalAddress = $_.LocalAddresses
FWRemoteAddress =  $_.RemoteAddresses
FWIcmpType= $_.ICMPType
FWDirection = switch($_.Direction) {
                                    1 {'Inbound'}
                                    2 {'Outbound'}
                                   }
FWAction = switch($_.Action)
                                    {
                                    1 {'Allow'}
                                    2 {'Deny'}

}
 }
 }
 
  $Header = @"
<style>
BODY{background-color:white;}
TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: LightBlue}
TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: white}
.green{background-color:#d5f2d5}
.blue{background-color:#277ece}
.red{background-color:#ff0004}
</style>
"@
 $PreContentHTML = "<hr>
                    <H3>Firewall Rules $env:COMPUTERNAME</H3>" 

$Rules|ConvertTo-HTML -head $Header -PreContent $PreContentHTML | Out-File "$ExportReport\$env:COMPUTERNAME.html"

In the end, I could read this report quickly and check/uncheck needed firewall rules.

Good Luck

About: admin