locked
Using PowerShell to Query Firewall Status RRS feed

  • General discussion

  • Someone asked this question in another post. When I called out the moderator for not knowing what he is talking about and provided the actual script to do this he deleted my comment. Good job at making Microsoft looking unprofessional jrv. It doesn't matter if netsh outputs to text as jrv says, it can be done. Script below to output to csv.

    Once it is all outputted to CSV to a replace to clean up all the extra space before the status. 

    Example

    Replace "Public Profile Settings:  ---------------------------------------------------------------------- State " 

    with ""

    #Queries all servers in ServersOU
    $Servers = (Get-ADComputer -filter * -searchbase "ou=ServersOU, dc=domain, dc=local" | select name | %{$_.name.trim()})

    #Creates C:\temp if it doesn't exist
    if ( -Not (Test-Path 'C:\temp' ))
     {
      Write-Host 'Creating temp folder'
      New-Item -Path 'C:\temp' -ItemType Directory
     }

    $Report = "C:\temp\FirewallStatus.csv"
    $TotalItems = ($Servers | Measure)
    $TotalItems = $Totalitems.Count

    $Services = @()

        $Table =@()
        $Record = @{
        "Server" = ""
        "ServiceName" = ""
        "ServiceStatus" = ""
        "DomainProfileFirewall" = ""
        "PrivateProfileFirewall" = ""
        "PublicProfileFirewall" = ""
        }

      [int]$Item = '1'  

    Foreach ($Server in $Servers)
    {

        Write-Host "Working on $Server"
        Write-Host "Working on item $Item of $TotalItems"
        $Item ++

            Try
            {
            $Service = Invoke-command -ComputerName $Server {Get-Service MpsSvc | select DisplayName,Status}
            [string]$Domain = Invoke-command -ComputerName $Server {netsh advfirewall show domain state}
            [string]$Private = Invoke-command -ComputerName $Server {netsh advfirewall show private state}
            [string]$Public = Invoke-command -ComputerName $Server {netsh advfirewall show public state}
            }

            Catch
            {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName
            }

                #If ($ErrorMessage -eq "" -or $ErrorMessage -eq $Null)
                #{   
                    $Record."Server" = $Server
                    $Record."ServiceName" = $Service.DisplayName
                    $Record."ServiceStatus" = $Service.Status
                    $Record."DomainProfileFirewall" = $Domain
                    $Record."PrivateProfileFirewall" = $Private
                    $Record."PublicProfileFirewall" = $Public
                    $objRecord = New-Object PSObject -property $Record
                    $Table += $objRecord
                #}

                <#ElseIF ($ErrorMessage -ne "")
                {
                Write-Host $ErrorMessage
                $ErrorMessages += $ErrorMessage
                }#>
    }


    $Table | Select Server,ServiceStatus,DomainProfileFirewall,PrivateProfileFirewall,PublicProfileFirewall |  Export-Csv -Path $Report -NoTypeInformation
    $ErrorMessages | Out-File "C:\temp\errormessagesfirewallstatus.txt"

            
    • Edited by JoeAlves1981 Monday, October 23, 2017 9:55 PM Added instructions to clean up csv for easier viewing
    Monday, October 23, 2017 9:46 PM

All replies

  • It is unproductive and rude to add to a closed 5 year old thread.  It is better to open a new question and be clear about hat you are asking,  The old thread was a simple question and the OP marked the answer that solved his issue and it is not clear why you would want to complain.

    Yes, today we have CmdLets to do all of this.  netsh is no longer needed.  If you want to share your script then the place to do that is the Gallery.  

    I recommend looking into the PowerShell firewall CmdLets.

    help *netfirewall*

    These CmdLets make automating and querying the firewall very easy.


    \_(ツ)_/

    Monday, October 23, 2017 10:00 PM
  • You are correct, if you are using 2012 R2 or higher. For older versions of Windows you still need to use netsh and create custom objects to join all the properties together in a way that makes sense. It can be done. If the post doesn't make sense anymore why not remove the entire post? It's still going to be relevant for a few years.
    Monday, October 23, 2017 10:56 PM
  • @JoeAlves1981: I needed something like this, decided to use your script and brush it up a little. Thanks!

    $minBuild = 7600
    $ADComputers = Get-ADComputer -Filter * -Properties CanonicalName,DNSHostName,IPv4Address,OperatingSystem,OperatingSystemVersion | `
                   ?{$_.OperatingSystem -match 'Windows.*Server' -and `
                     ($_.OperatingSystemVersion -Replace '[^\s]+\s|\(|\)').ToInt32($Null) -ge $minBuild} | Sort CanonicalName
    $Servers = ($ADComputers | Select Name | %{$_.Name.Trim()})
    
    $TotalItems = ($Servers | Measure)
    $TotalItems = $Totalitems.Count
    $Services = @()
    $Results = @()
    $Item = 1
    Foreach ($Server in $Servers) {
    	Write-Progress -Activity "Retrieving firewall status" `
    			       -Status "Querying $($Server): [$Item/$TotalItems]" `
    			       -PercentComplete ([math]::Ceiling(100/$($Servers.Count)*$Item))
        $Item++
    	try {
    		$return = (Invoke-Command -CN $Server -ScriptBlock {
    			(Get-Service MpsSvc | select DisplayName,Status | ft -a | Out-String).Trim()
    			netsh advfirewall show domain state
    			netsh advfirewall show private state
    			netsh advfirewall show public state
    		} | Out-String).Trim() -Split '\r\n'
    		#$return
    		If ($return[2] -match 'Running') {
    			$ServiceName = ($return[2] -Split '\s+' | Select -Last ($($return.Count)-1) -Skip 1) -Join ' '
    			$ServiceStatus = $True
    		} Else { $ServiceName = $Null; $ServiceStatus = $Null }
    		If ($return[4]  -match 'Domain Profile')  { $Domain  = $return[6]  -Split '\s' | Select -Last 1 } Else { $Domain  = $Null }
    		If ($return[10] -match 'Private Profile') { $Private = $return[12] -Split '\s' | Select -Last 1 } Else { $Private = $Null }
    		If ($return[16] -match 'Public Profile')  { $Public  = $return[18] -Split '\s' | Select -Last 1 } Else { $Public  = $Null }
    		Write-Host "$Server `"$ServiceName`" $ServiceStatus $Domain $Private $Public"
    	} catch {
    		Write-Host -Back Black -Fore Red "$($_.Exception.Message);$($_.Exception.ItemName)"
    	}
    	$Results += [pscustomobject]@{'Server'        = $Server
                                    'ServiceName'   = $ServiceName
                                    'ServiceStatus' = $ServiceStatus
                                    'StateDomain'   = $Domain
                                    'StatePrivate'  = $Private
                                    'StatePublic'   = $Public}
    }
    $Results | ?{$_.StateDomain,$_.StatePrivate,$_.StatePublic -contains 'OFF'} | ft -a
    #$Results | Out-Gridview

    Monday, January 14, 2019 11:58 PM
  • Hey VBdP,

    I have been trying to get your modified script to output to a CSV or txt file, but have not had any luck. It will create the file, but it will be blank. Any help would be much appreciated!

    Thanks,

    Al

    Thursday, February 6, 2020 10:09 PM