Get Application Pools using PowerShell function

Getting Application Pools status remotely is relatively easy. Adding them into a data table and then sending it in html formatted report is more complex process. Today I would like to show how to do this by breaking apart one of my functions.

In one of the previous articles I described how to get status of application pools and additionally reset IIS if needed – link. This time we just want to have a nice output in html formatted report.

Function is based on Get-WebAppPoolState command which is part of WebAdministration module:

(Get-Command -Name Get-WebAppPoolState).module #Check commands module name
Get-WebAppPoolState -Name *DefaultAppPool* | Select-Object *

While running this function we will have possibility to choose if we want to display results in console or send email with report -SendEmail.

Get-AppPool -ComputerName Server01,Server02 -SendEmail No | FT -Wrap -AutoSize
Get-AppPool -ComputerName Server01,Server02 -SendEmail Yes

Output in PS console:

Get-AppPool
Get-AppPool

Html formatted report with successful results:

AppPools Report
AppPools Report

In case of failure results status will be marked with red background:

AppPools Report failure
AppPools Report failure

To do this we need to point which key words should be marked in red background color. In this example those words would be stopped, query error and unknown:

                $colorTagTable = @{ 
                                    Stopped = ' bgcolor="red">Stopped<';
                                    "Query Error" = ' bgcolor="red">Query Error<';
                                    Unknown = ' bgcolor="red">Unknown<'
 
                                    }
  
                $colorTagTable.Keys | foreach { $body = $body -replace ">$_<",($colorTagTable.$_) } 

Remember to add to ValidateSet your web application pools names:

[Parameter(Position=1, Mandatory = $false, HelpMessage="Provide app pool name", ValueFromPipeline = $false)] 
[ValidateSet('NET v4.5','NET v4.5 Classic',"DefaultAppPool","Sign On","SharePoint","Mobile")]
$AppPool = "All",

Please also ensure that SMTP and email addresses are properly added:


                    # Setup email parameters
                    $Date = (Get-Date).ToString('MMMM-dd')
                    $mailTo = ((Get-ADUser -Identity $ENV:Username -Properties mail).mail ) 
                    $subject = ”AppPools Report - ” + $Date
                    $priority = ”Normal”
                    $smtpServer = "smtp.powershellbros.com"
                    $emailFrom = ”Reports@powershellbros.com”
                    $emailTo = $mailTo
                    $port = 25 

                    #Send email
                    Send-MailMessage -ErrorAction Stop -To $emailTo -Subject $subject -BodyAsHtml $body -SmtpServer $smtpServer -port $port -From $emailFrom -Priority $priority

Usage:

Get-AppPool
Get-AppPool -Computername DC01
Get-AppPool -Computername DC01,DCO2,DC03
Get-AppPool -Computername DC01,DCO2,DC03 -SendEmail Yes
Get-AppPool -Computername DC01,DCO2,DC03 -AppPool "NET v4.5" | Format-Table -Wrap -AutoSize
Get-AppPool -Computername (Get-Content -Path "c:\temp\servers.txt") -AppPool "NET v4.5","SharePoint"  | Format-Table -Wrap -AutoSize
Get-AppPool -Computername (Get-Content -Path "c:\temp\servers.txt") -SendEmail Yes -Verbose
Get-Content -Path "c:\temp\servers.txt" | Get-AppPool 

Final script:

Function Get-AppPool {
        [CmdletBinding()]
               
        # Parameters used in this function
        param
        (
            [Parameter(Position=0, Mandatory = $false, HelpMessage="Provide server names", ValueFromPipeline = $true)] 
            $Computername = $env:computername,
   
            [Parameter(Position=1, Mandatory = $false, HelpMessage="Provide app pool name", ValueFromPipeline = $false)] 
            [ValidateSet('NET v4.5','NET v4.5 Classic',"DefaultAppPool","Sign On","SharePoint","Mobile")]
            $AppPool = "All",

            [Parameter(Position=2, Mandatory = $false, HelpMessage="Do you want to recevie email?", ValueFromPipeline = $false)]
            [ValidateSet("Yes","No")]
            $SendEmail = "No"
        ) 

        # Creating table
        $tabName = “AppPoolsReport”

        #Create Table object
        $table = New-Object system.Data.DataTable “$tabName”

        # Set AppPools list
        If($AppPool -eq "All")
        {
            $AppPoolsList = 'NET v4.5','NET v4.5 Classic',"DefaultAppPool","Sign On","SharePoint","Mobile"
        }
        Else
        {
            $AppPoolsList = $AppPool
        }

        #Add server column
        $table.columns.add( (New-Object system.Data.DataColumn 'Server name',([string])) )
           
        #Loop each server
        Foreach($Server in $ComputerName)
        {
            Write-Verbose "Processing $server"
            
            # Create new row for first server
            $row = $table.NewRow()
            $row.”Server name” = $Server
            
            #Loop each AppPool
            ForEach( $AppPool in $AppPoolsList )
            {
                Write-Verbose "Checking $AppPool"
                $Status = $null
                $AppItem = $null
                
                Try
                {
                    $AppItem = (Invoke-Command $Server -ScriptBlock{param($AppPool) Get-WebAppPoolState -Name *$AppPool* } -ArgumentList $AppPool )[0]
                }
                Catch
                {
                    $ErrorCheck = $_.Exception.Message
                }
                                  
                If($AppItem)
                {
                    $name = ($appitem.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1').Trim()
                    $Status = ($AppItem.value).trim()
                }
                ElseIf($ErrorCheck)
                {
                    $name = $AppPool
                    $Status = "Query Error"    
                }
                Else
                {
                    $name = $AppPool
                    $Status = "Unknown"
                }
                
                Try
                {
                    #Create new column
                    $table.columns.add( (New-Object system.Data.DataColumn "$name",([string])) )
                    $row.”$name” = $Status
                }
                Catch
                {
                    #Add value if App column name already exist
                    $row.”$name” = $Status
                    Continue
                }
            }
                 
        # Add row to a table
        $table.Rows.Add($row)

        }

#Proceed if table created
If($table)
{
    If($SendEmail -eq "No")
    {
        Return [PSCustomObject]$table | Select-Object -ExcludeProperty RowError, RowState, Table, ItemArray, HasErrors 
    }
    Else
    {

#=======================================================================
#Creating head style 
$Head = @"
<style>
  body {
    font-family: "Arial";
    font-size: 8pt;
    }
  th, td, tr { 
    border: 1px solid #e57300;
    border-collapse: collapse;
    padding: 7px;
    text-align: center;
    }
  th {
    font-size: 9;
    text-align: center;
    background-color: #003366;
    color: #ffffff;
    }
  td {
    color: #000000;
     
    }
  .even { background-color: #ffffff; }
  .odd { background-color: #bfbfbf; }
  h6 { font-size: 15pt; 
       font-color: black;
       font-weight: bold;
       }

text { font-size: 14pt;
        font-color: black;
        }
}
</style>
"@

$pre = @"
<div class="text">
Hi Team,<br/>
Please find the report for <strong>AppPools status</strong>.<br/>
                 
<br/>
</div>
"@
  
$post = @"
<div class="text">
<br/>
<strong>Kind Regards</strong><br>PowerShellBros<br/>
<br/></div>
"@
#=======================================================================

                #Create body for email message
                [string]$Body = [PSCustomObject]$table | Select-Object * -ExcludeProperty RowError, RowState, Table, ItemArray, HasErrors | 
                ConvertTo-HTML -head $head -PreContent $pre -PostContent $post 
  
                $colorTagTable = @{ 
                                    Stopped = ' bgcolor="red">Stopped<';
                                    "Query Error" = ' bgcolor="red">Query Error<';
                                    Unknown = ' bgcolor="red">Unknown<'

                                    }
 
                $colorTagTable.Keys | foreach { $body = $body -replace ">$_<",($colorTagTable.$_) } 

                Try
                {
                    # Setup email parameters
                    $Date = (Get-Date).ToString('MMMM-dd')
                    $mailTo = ((Get-ADUser -Identity $ENV:Username -Properties mail).mail ) 
                    $subject = ”AppPools Report - ” + $Date
                    $priority = ”Normal”
                    $smtpServer = "smtp.powershellbros.com"
                    $emailFrom = ”Reports@powershellbros.com”
                    $emailTo = $mailTo
                    $port = 25 

                    #Send email
                    Send-MailMessage -ErrorAction Stop -To $emailTo -Subject $subject -BodyAsHtml $body -SmtpServer $smtpServer -port $port -From $emailFrom -Priority $priority
                }
                Catch
                {
                    $SendError = $_.Exception.Message 
                    Continue
                }
                If(!$SendError)
                {
                    Write-Warning "Email has been sent to $emailto"
                }
                Else
                {
                    Return $SendError
                }
    }
}

}

I hope that this was informative for you and see you in next articles 🙂

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.