Featured post

Automation | Powershell scripts

Automation | Powershell scripts Xenapp 6.5 Health check script XenAppServerHealthCheck Report through Script  ## XenAppServerHealthCheck ## ...

Friday, 18 February 2022

Automation | Powershell scripts

Automation | Powershell scripts

Xenapp 6.5 Health check script

XenAppServerHealthCheck Report through Script 




## XenAppServerHealthCheck

## The script checks the health of a XenApp 6.x farm and e-mails two reports. The full farm

## health report is attached to the e-mail and any errors encountered are in an html report

## embedded in the email body.

## This script checks the following:

##   - Ping response

##   - Logon enabled

##   - Assigned Load Evaluator

##   - Active sessions

##   - ICA port response 

##   - CGP port response (session reliability)

##   - WMI response (to check for WMI corruption)

##   - Citrix IMA, Citrix XML, Citrix Print Manager and Spooler services

##   - Server uptime (to ensure scheduled reboots are occurring)

##   - Server folder path and worker group memberships are report for informational purposes

##   - PVS vDisk and write cache file size

## 

## Change history:

##   2.7 - Fixed bug with Check Services 

##   2.6 - Added support for unique load evaluators and PVS vDisks per server silo (based on 

##         server folder path). This functionality is in the $allSiloInfo hash table data 

##         structure.

##   2.5 - Added support for Cache in device RAM overflow to disk PVS option, now queries running 

##         services once for each server speeding up the script.

##   2.4 - Changed default Load Evaluator to handle multiple values; updated Ping routine to be 

##         more robust.

## 

## TO DO

##   - Rewrite for XA/XD 7.x!!

##   - Add unique user count

##   - Move per environment variable data to an XML file

##   - PVS server health check

##   - Incorporate Medvac??

## 

## You are free to use this script in your environment but please e-mail me any improvements.

################################################################################################

if ((Get-PSSnapin "Citrix.XenApp.Commands" -EA silentlycontinue) -eq $null) {

try { Add-PSSnapin Citrix.XenApp.Commands -ErrorAction Stop }

catch { write-error "Error loading XenApp Powershell snapin"; Return }

}

 

# Change the below variables to suit your environment

#==============================================================================================

# Default load evaluator assigned to servers. Can have multiple values in format "LE1", "LE2",

# if a match is made to ANY of the listed LEs SUCCESS is returned for the LE check.

$defaultLE       = "Servers"


# Default PVS vDisk assigned to servers

$defaultVDisk    = "XA6_Desktop_1"


# Relative path to the PVS vDisk write cache file

$PvsWriteCache   = "d$\.vdiskcache"

$PvsWriteCache2  = "d$\vdiskdif.vhdx"


# Maximum size of the local PVS write cache file

$PvsWriteMaxSize = 8gb # size in GB


# Servers in the excluded folders will not be included in the health check

$excludedFolders = @("Servers/Test","Servers/Turned Off")

 

# We always schedule reboots on XenApp farms, usually on a weekly basis. Set the maxUpTimeDays

# variable to the maximum number of days a XenApp server should be up for.

$maxUpTimeDays = 7


# E-mail report details

$emailFrom     = "XenAppFarmReport@acme.co.nz"

$emailTo       = "citrix.admins@acme.co.nz"

$smtpServer    = "mail.acme.co.nz"

$emailSubject  = ("XenApp Farm Report - " + (Get-Date -format R))


# Silo info

$allSiloInfo = @{}

$siloInfo    = @{}

# Uncomment the below to enable silo support

# Copy the below four line as many time as required - once for each silo to be supported.

#$siloInfo.name  = "Servers/Production"

#$siloInfo.LE    = "Productions Servers"

#$siloInfo.vDisk = "XA6_Desktop_1"

#$allSiloInfo.($siloInfo.name) = $siloInfo


# Only change this if you have changed the Session Reliability port from the default of 2598

$sessionReliabilityPort = "2598"


#==============================================================================================

 

$currentDir = Split-Path $MyInvocation.MyCommand.Path

$logfile    = Join-Path $currentDir ("XenAppServerHealthCheck.log")

$resultsHTM = Join-Path $currentDir ("XenAppServerHealthCheckResults.htm")

$errorsHTM  = Join-Path $currentDir ("XenAppServerHealthCheckErrors.htm")

 

$headerNames  = "FolderPath", "WorkerGroups", "ActiveSessions", "ServerLoad", "Ping", "Logons", "LoadEvaluator", "ICAPort", "CGPPort", "IMA", "CitrixPrint", "WMI", "XML", "Spooler", "Uptime", "WriteCacheSize", "vDisk"

$headerWidths = "6",          "6",            "4",              "4",          "4",    "6",      "6",             "4",       "6",                  "4",   "4",           "4",   "4",   "4",       "5",      "4",              "4"


#==============================================================================================

function LogMe() {

Param(

[parameter(Mandatory = $true, ValueFromPipeline = $true)] $logEntry,

[switch]$display,

[switch]$error,

[switch]$warning,

[switch]$progress

)



if ($error) {

$logEntry = "[ERROR] $logEntry" ; Write-Host "$logEntry" -Foregroundcolor Red}

elseif ($warning) {

Write-Warning "$logEntry" ; $logEntry = "[WARNING] $logEntry"}

elseif ($progress) {

Write-Host "$logEntry" -Foregroundcolor Green}

elseif ($display) {

Write-Host "$logEntry" }

 

#$logEntry = ((Get-Date -uformat "%D %T") + " - " + $logEntry)

$logEntry | Out-File $logFile -Append

}



#==============================================================================================

function Ping([string]$hostname, [int]$timeout = 1000, [int]$retries = 3) {

$result = $true

$ping = new-object System.Net.NetworkInformation.Ping #creates a ping object

$i = 0

do {

$i++

#write-host "Count: $i - Retries:$retries"

try {

#write-host "ping"

$result = $ping.send($hostname, $timeout).Status.ToString()

} catch {

#Write-Host "error"

continue

}

if ($result -eq "success") { return $true }

} until ($i -eq $retries)

return $false

}



#==============================================================================================

Function writeHtmlHeader

{

param($title, $fileName)

$date = ( Get-Date -format R)

$head = @"

<html>

<head>

<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>

<title>$title</title>

<STYLE TYPE="text/css">

<!--

td {

font-family: Tahoma;

font-size: 11px;

border-top: 1px solid #999999;

border-right: 1px solid #999999;

border-bottom: 1px solid #999999;

border-left: 1px solid #999999;

padding-top: 0px;

padding-right: 0px;

padding-bottom: 0px;

padding-left: 0px;

overflow: hidden;

}

body {

margin-left: 5px;

margin-top: 5px;

margin-right: 0px;

margin-bottom: 10px;

table {

table-layout:fixed; 

border: thin solid #000000;

}

-->

</style>

</head>

<body>

<table width='1200'>

<tr bgcolor='#CCCCCC'>

<td colspan='7' height='48' align='center' valign="middle">

<font face='tahoma' color='#003399' size='4'>

<!--<img src="http://servername/administration/icons/xenapp.png" height='42'/>-->

<strong>$title - $date</strong></font>

</td>

</tr>

</table>

<table width='1200'>

<tr bgcolor='#CCCCCC'>

<td width=50% height='48' align='center' valign="middle">

<font face='tahoma' color='#003399' size='4'>

<!--<img src="http://servername/administration/icons/active.png" height='32'/>-->

Active Sessions:  $TotalActiveSessions</font>

<td width=50% height='48' align='center' valign="middle">

<font face='tahoma' color='#003399' size='4'>

<!--<img src="http://servername/administration/icons/disconnected.png" height='32'/>-->

Disconnected Sessions:  $TotalDisconnectedSessions</font>

</td>

</tr>

</table>

"@

$head | Out-File $fileName

}


# ==============================================================================================

Function writeTableHeader

{

param($fileName)

$tableHeader = @"

<table width='1200'><tbody>

<tr bgcolor=#CCCCCC>

<td width='6%' align='center'><strong>ServerName</strong></td>

"@


$i = 0

while ($i -lt $headerNames.count) {

$headerName = $headerNames[$i]

$headerWidth = $headerWidths[$i]

$tableHeader += "<td width='" + $headerWidth + "%' align='center'><strong>$headerName</strong></td>"

$i++

}


$tableHeader += "</tr>"


$tableHeader | Out-File $fileName -append

}


# ==============================================================================================

Function writeData

{

param($data, $fileName)

$data.Keys | sort | foreach {

$tableEntry += "<tr>"

$computerName = $_

$tableEntry += ("<td bgcolor='#CCCCCC' align=center><font color='#003399'>$computerName</font></td>")

#$data.$_.Keys | foreach {

$headerNames | foreach {

#"$computerName : $_" | LogMe -display

try {

if ($data.$computerName.$_[0] -eq "SUCCESS") { $bgcolor = "#387C44"; $fontColor = "#FFFFFF" }

elseif ($data.$computerName.$_[0] -eq "WARNING") { $bgcolor = "#FF7700"; $fontColor = "#FFFFFF" }

elseif ($data.$computerName.$_[0] -eq "ERROR") { $bgcolor = "#FF0000"; $fontColor = "#FFFFFF" }

else { $bgcolor = "#CCCCCC"; $fontColor = "#003399" }

$testResult = $data.$computerName.$_[1]

}

catch {

$bgcolor = "#CCCCCC"; $fontColor = "#003399"

$testResult = ""

}

$tableEntry += ("<td bgcolor='" + $bgcolor + "' align=center><font color='" + $fontColor + "'>$testResult</font></td>")

}

$tableEntry += "</tr>"

}

$tableEntry | Out-File $fileName -append

}


 

# ==============================================================================================

Function writeHtmlFooter

{

param($fileName)

@"

</table>

<table width='1200'>

<tr bgcolor='#CCCCCC'>

<td colspan='7' height='25' align='left'>

<font face='courier' color='#003399' size='2'><strong>Default Load Evaluator  = $DefaultLE</strong></font>

<tr bgcolor='#CCCCCC'>

<td colspan='7' height='25' align='left'>

<font face='courier' color='#003399' size='2'><strong>Default VDISK Image         = $DefaultVDISK</strong></font>

</td>

</tr>

</table>

</body>

</html>

"@ | Out-File $FileName -append

}


Function Check-Port  

{

param ([string]$hostname, [string]$port)

try {

#$socket = new-object System.Net.Sockets.TcpClient($ip, $_.IcaPortNumber) #creates a socket connection to see if the port is open

$socket = new-object System.Net.Sockets.TcpClient($hostname, $Port) #creates a socket connection to see if the port is open

} catch {

$socket = $null

"Socket connection failed" | LogMe -display -error

return $false

}


if($socket -ne $null) {

"Socket Connection Successful" | LogMe

if ($port -eq "1494") {

$stream   = $socket.GetStream() #gets the output of the response

$buffer   = new-object System.Byte[] 1024

$encoding = new-object System.Text.AsciiEncoding


Start-Sleep -Milliseconds 500 #records data for half a second

while($stream.DataAvailable)

{

$read     = $stream.Read($buffer, 0, 1024)  

$response = $encoding.GetString($buffer, 0, $read)

#Write-Host "Response: " + $response

if($response -like '*ICA*'){

"ICA protocol responded" | LogMe

return $true

}

"ICA did not response correctly" | LogMe -display -error

return $false

} else {

return $true

}

   

} else { "Socket connection failed" | LogMe -display -error; return $false }

}


# ==============================================================================================

# ==                                       MAIN SCRIPT                                        ==

# ==============================================================================================

"Checking server health..." | LogMe -display


rm $logfile -force -EA SilentlyContinue


# Data structure overview:

# Individual tests added to the tests hash table with the test name as the key and a two item array as the value.

# The array is called a testResult array where the first array item is the Status and the second array

# item is the Result. Valid values for the Status are: SUCCESS, WARNING, ERROR and $NULL.

# Each server that is tested is added to the allResults hash table with the computer name as the key and

# the tests hash table as the value.

# The following example retrieves the Logons status for server NZCTX01:

# $allResults.NZCTX01.Logons[0]


$allResults = @{}


# Get session list once to use throughout the script

$sessions = Get-XASession

 

Get-XAServer | % {


$tests = @{}

$server = $_.ServerName

# Check to see if the server is in an excluded folder path

$folderPath = $_.FolderPath 

#$excludedFolders | ? { $_ -like $folderPath } | { $server + " in excluded folder - skipping" | LogMe; return }

if ($excludedFolders -contains $_.FolderPath) { $server + " in excluded folder - skipping" | LogMe; return }

$server | LogMe -display -progress

    

    if ($allSiloInfo.$folderPath) {

        # Silo specific info is available

        if (($allSiloInfo.$folderPath).LE)    { $serverLE    = ($allSiloInfo.$folderPath).LE }

        if (($allSiloInfo.$folderPath).vDisk) { $serverVDisk = ($allSiloInfo.$folderPath).vDisk }

    } else {

        $serverLE    = $defaultLE

        $serverVDisk = $defaultVDisk

    }

$tests.FolderPath   = $null, $_.FolderPath

$tests.WorkerGroups = $null, (Get-XAWorkerGroup -ServerName $server | % {$_.WorkerGroupName})

if ($_.CitrixVersion -ge 6.5) { $minXA65 = $true }

else { $minXA65 = $false }


# Check server logons

if($_.LogOnsEnabled -eq $false){

"Logons are disabled on this server" | LogMe -display -warning

$tests.Logons = "WARNING", "Disabled"

} else {

$tests.Logons = "SUCCESS","Enabled"

}

# Report on active server sessions

$activeServerSessions = [array]($sessions | ? {$_.State -eq "Active" -and $_.Protocol -eq "Ica" -and $_.ServerName -match $server})

if ($activeServerSessions) { $totalActiveServerSessions = $activeServerSessions.count }

# the  following line will return unique users rather than active sessions

#if ($activeServerSessions) { $totalActiveServerSessions = ($activeServerSessions | Group-Object -property AccountName).count }

else { $totalActiveServerSessions = 0 }

$tests.ActiveSessions = $null, $totalActiveServerSessions

# Check Load Evaluator

$assignedLE = (Get-XALoadEvaluator -ServerName $_.ServerName).LoadEvaluatorName

if ($serverLE -notcontains $assignedLE) {

"Non-default Load Evaluator assigned" | LogMe -display -warning

$tests.LoadEvaluator = "WARNING", $assignedLE

} else {

$tests.LoadEvaluator = "SUCCESS", $assignedLE

}


# Ping server 

$result = Ping $server 100

if ($result -ne "SUCCESS") { $tests.Ping = "ERROR", $result }

else { $tests.Ping = "SUCCESS", $result 

# Test ICA connectivity

if (Check-Port $server $_.IcaPortNumber) { $tests.ICAPort = "SUCCESS", "Success" }

else { $tests.ICAPort = "ERROR","No response" }

# Test Session Reliability port

if (Check-Port $server $sessionReliabilityPort) { $tests.CGPPort = "SUCCESS", "Success" }

else { $tests.CGPPort = "ERROR", "No response" }

# Check services

$services = Get-Service -Computer $Server

if (($services | ? {$_.Name -eq "IMAService"}).Status -Match "Running") {

"IMA service running..." | LogMe

$tests.IMA = "SUCCESS", "Success"

} else {

"IMA service stopped"  | LogMe -display -error

$tests.IMA = "ERROR", "Error"

}

if (($services | ? {$_.Name -eq "Spooler"}).Status -Match "Running") {

"SPOOLER service running..." | LogMe

$tests.Spooler = "SUCCESS","Success"

} else {

"SPOOLER service stopped"  | LogMe -display -error

$tests.Spooler = "ERROR","Error"

}

if (($services | ? {$_.Name -eq "cpsvc"}).Status -Match "Running") {

"Citrix Print Manager service running..." | LogMe

$tests.CitrixPrint = "SUCCESS","Success"

} else {

"Citrix Print Manager service stopped"  | LogMe -display -error

$tests.CitrixPrint = "ERROR","Error"

}

if (($minXA65 -and $_.ElectionPreference -ne "WorkerMode") -or (!($minXA65))) {

if (($services | ? {$_.Name -eq "ctxhttp"}).Status -Match "Running") {

"XML service running..." | LogMe

$tests.XML = "SUCCESS","Success"

} else {

"XML service stopped"  | LogMe -display -error

$tests.XML = "ERROR","Error"

}   

} else { $tests.XML = "SUCCESS","N/A" }

# If the IMA service is running, check the server load

if ($tests.IMA[0] -eq "Success") {

try {

$CurrentServerLoad = Get-XAServerLoad -ServerName $server

#$CurrentServerLoad.GetType().Name|LogMe -display -warning

if( [int] $CurrentServerLoad.load -lt 7500) {

  "Serverload is low" | LogMe

  $tests.Serverload = "SUCCESS", ($CurrentServerload.load)

}

elseif([int] $CurrentServerLoad.load -lt 9000) {

"Serverload is Medium" | LogMe -display -warning

$tests.Serverload = "WARNING", ($CurrentServerload.load)

}   

else {

"Serverload is High" | LogMe -display -error

$tests.Serverload = "ERROR", ($CurrentServerload.load)

}   

}

catch {

"Error determining Serverload" | LogMe -display -error

$tests.Serverload = "ERROR", ($CurrentServerload.load)

}

$CurrentServerLoad = 0

}



# Test WMI

$tests.WMI = "ERROR","Error"

try { $wmi=Get-WmiObject -class Win32_OperatingSystem -computer $_.ServerName } 

catch { $wmi = $null }


# Perform WMI related checks

if ($wmi -ne $null) {

$tests.WMI = "SUCCESS", "Success"

$LBTime=$wmi.ConvertToDateTime($wmi.Lastbootuptime)

[TimeSpan]$uptime=New-TimeSpan $LBTime $(get-date)


if ($uptime.days -gt $maxUpTimeDays){

"Server reboot warning, last reboot: {0:D}" -f $LBTime | LogMe -display -warning

$tests.Uptime = "WARNING", $uptime.days

} else {

$tests.Uptime = "SUCCESS", $uptime.days

}

} else { "WMI connection failed - check WMI for corruption" | LogMe -display -error }


################ PVS SECTION ###############

if (test-path \\$Server\c$\Personality.ini) {

$PvsWriteCacheUNC = Join-Path "\\$Server" $PvsWriteCache 

$CacheDiskexists  = Test-Path $PvsWriteCacheUNC


if ($CacheDiskexists -eq $False) {

$PvsWriteCacheUNC = Join-Path "\\$Server" $PvsWriteCache2

$CacheDiskexists  = Test-Path $PvsWriteCacheUNC

}



if ($CacheDiskexists -eq $True)

{

$CacheDisk = [long] ((get-childitem $PvsWriteCacheUNC -force).length)

$CacheDiskGB = "{0:n2}GB" -f($CacheDisk / 1GB)

"PVS Cache file size: {0:n2}GB" -f($CacheDisk / 1GB) | LogMe

#"PVS Cache max size: {0:n2}GB" -f($PvsWriteMaxSize / 1GB) | LogMe -display

if($CacheDisk -lt ($PvsWriteMaxSize * 0.5))

{

   "WriteCache file size is low" | LogMe

   $tests.WriteCacheSize = "SUCCESS", $CacheDiskGB

}

elseif($CacheDisk -lt ($PvsWriteMaxSize * 0.8))

{

   "WriteCache file size moderate" | LogMe -display -warning

   $tests.WriteCacheSize = "WARNING", $CacheDiskGB

}   

else

{

   "WriteCache file size is high" | LogMe -display -error

   $tests.WriteCacheSize = "ERORR", $CacheDiskGB

}

}              

   

$Cachedisk = 0

   

$VDISKImage = get-content \\$Server\c$\Personality.ini | Select-String "Diskname" | Out-String | % { $_.substring(12)}

if($VDISKImage -Match $serverVDisk){

"Default vDisk detected" | LogMe

$tests.vDisk = "SUCCESS", $VDISKImage

} else {

"vDisk unknown"  | LogMe -display -error

$tests.vDisk = "WARNING", $VDISKImage

}   

}

else { $tests.WriteCacheSize = "SUCCESS", "N/A";  $tests.vDisk = "SUCCESS", "N/A" }

############## END PVS SECTION #############

}


$allResults.$server = $tests

}


# Get farm session info

$ActiveSessions       = [array]($sessions | ? {$_.State -eq "Active" -and $_.Protocol -eq "Ica"})

$DisconnectedSessions = [array]($sessions | ? {$_.State -eq "Disconnected" -and $_.Protocol -eq "Ica"})


if ($ActiveSessions) { $TotalActiveSessions = $ActiveSessions.count }

# the  following line will return unique users rather than active sessions

# if ($activeSessions) { $totalActiveSessions = ($activeSessions | Group-Object -property AccountName).count }

else { $TotalActiveSessions = 0 }


if ($DisconnectedSessions) { $TotalDisconnectedSessions = $DisconnectedSessions.count }

else { $TotalDisconnectedSessions = 0 }


"Total Active Sessions: $TotalActiveSessions" | LogMe -display

"Total Disconnected Sessions: $TotalDisconnectedSessions" | LogMe -display


# Write all results to an html file

Write-Host ("Saving results to html report: " + $resultsHTM)

writeHtmlHeader "XenApp Farm Report" $resultsHTM

writeTableHeader $resultsHTM

$allResults | sort-object -property FolderPath | % { writeData $allResults $resultsHTM }

writeHtmlFooter $resultsHTM


# Write only the errors to an html file

#$allErrors = $allResults | where-object { $_.Ping -ne "success" -or $_.Logons -ne "enabled" -or $_.LoadEvaluator -ne "default" -or $_.ICAPort -ne "success" -or $_.IMA -ne "success" -or $_.XML -ne "success" -or $_.WMI -ne "success" -or $_.Uptime -Like "NOT OK*" }

#$allResults | % { $_.Ping -ne "success" -or $_.Logons -ne "enabled" -or $_.LoadEvaluator -ne "default" -or $_.ICAPort -ne "success" -or $_.IMA -ne "success" -or $_.XML -ne "success" -or $_.WMI -ne "success" -or $_.Uptime -Like "NOT OK*" }

#Write-Host ("Saving errors to html report: " + $errorsHTM)

#writeHtmlHeader "XenApp Farm Report Errors" $errorsHTM

#writeTableHeader $errorsHTM

#$allErrors | sort-object -property FolderPath | % { writeData $allErrors $errorsHTM }

#writeHtmlFooter $errorsHTM


($mailMessageParameters = @{

From       = $emailFrom

To         = $emailTo

Subject    = $emailSubject

SmtpServer = $smtpServer

Body       = (gc $resultsHTM) | Out-String

Attachment = $resultsHTM

}


Send-MailMessage @mailMessageParameters -BodyAsHtml)


$mailMessageParameters = @{


from = “abc@co.com”

to = “xyz@coi.com”
Subject = “XenApp6 Health Check Report”
body = get-content “C:\Temp\XenApp 6.x\XenAppServerHealthCheckResults.htm” | Out-String
attachments = “C:\Temp\XenApp 6.x\XenAppServerHealthCheckResults.htm”
smtpserver = “10.0.0.1”
}
Send-MailMessage @mailMessageParameters -BodyAsHtml






Xenapp 7. X Health check script






#Saving Folder Path in a variable
$scriptPath     ="C:\Citrix_Script\"

#give PVS server FQDN/IP for monitoring Services
#$pvsServer = "001"

#Give environment name which will be shown in report
$environmentName = "XenApp"

#give FQDN if delivery controller is on remote server, give "localhost" if script is on delivery controller
$deliveryControllers = "localhost"

#mention drive letters of delivery controller to be monitored for freespace
$diskLettersControllers = @("C","D","G")

#Raise notification if delivery controllers have been rebooted in less than this number of days
$minUpTimeDaysDDC = "1"

#Maximum uptime of a XenApp
$maxUpTimeDays = "20"

#Exclude Tags, e.g excludeFromReport, UAT, etc 
$excludedTags = @()

#define the maximum of counted machines (default is only 250)
$maxMachines = "1000"

#Define(set as 1) if you ONLY want to see bad XENAPP (Unregistered, to high Uptime, Ping-Time-out) set this value to 1 in big environments (more than 50desktops)
$showOnlyErrorXA = "1"

#Set to 1 if you want to Check a Environment with XenApp (V 7.x and higher)
$showXenAppTable = "1"

#mention drive letters of XenApp server to be monitored for freespace
$diskLettersWorkers = @("C","D","E","G")

#Set to 1 if you want to see connected XenApp Users 
$showConnectedXenAppUsers = "1"

#Set value for a load of a XenApp server that is fine, but is needed to show warning 
$loadIndexWarning = "8000"

#Set value for a load of a XenApp server that is critical 
$loadIndexError = "10000"

#Address of the sender 
$emailFrom = "wintel_CitrixProd@abc.com"

#Address of the recipient 
$emailTo ="Citrix.in@abc.com"

#Address of the cc
$emailCc ="windows@abc.com","wintel.in@abc.com", "monitoring.in@abc.com"

#IP or name of SMTP server 
$smtpServer = "10.0.0.1"

#error in Xenapp server
$mailAlert = 0

#getting server current time in hours
$currentTime = (Get-date).Hour 

#server time in hour for mail to be sent
$triggerHour = 6 #24hr clock

#==============================================================================================

#==============================================================================================
#==============================================================================================
#==============================================================================================
#==============================================================================================
###############################################################################################
######################################### MAIN SCRIPT #########################################
###############################################################################################
$wmiOSBlock = {param($computer)
  try { $wmi=Get-WmiObject -class Win32_OperatingSystem -computer $computer }
  catch { $wmi = $null }
  return $wmi
  }
#==============================================================================================
# Loading only those snap-ins, which are used
if ((Get-PSSnapin "Citrix.Broker.Admin.*" -EA silentlycontinue) -eq $null) {
try { Add-PSSnapin Citrix.Broker.Admin.* -ErrorAction Stop }
catch { write-error "Error Get-PSSnapin Citrix.Broker.Admin.* Powershell snapin"; Return }
}
#==============================================================================================
#==============================================================================================

#Testing Connectivity to all Controllers servers
ForEach ($deliveryController in $deliveryControllers)
    {
            If ($deliveryController -ieq "LocalHost")
            {
               $deliveryController = [System.Net.DNS]::GetHostByName('').HostName
            }
             If (Test-Connection $deliveryController)
            {
                $adminAddress = $deliveryController
                break
            }
    }

#==============================================================================================
$reportDate = (Get-Date -UFormat "%A, %d. %B %Y %R")

#Getting path details in variables
$currentDir = Split-Path $scriptPath              
$outputPath = Join-Path $currentDir "\Citrix_Script\" #add here a custom output folder if you wont have it on the same directory
$outputdate = Get-Date -Format 'yyyyMMddHHmm'
$logFile = Join-Path $outputPath ("CTXXAMonitoringReport.log")
$resultsHTM = Join-Path $outputPath ("CTXXAMonitoringReport.htm") #add $outputdate in filename as per requirement using $reportDate variable

#==============================================================================================  


#Header for Table "XA Controllers" Get-BrokerController
$xaControllerFirstHeaderName = "ControllerServer HealthCheck"
$xaControllerHeaderNames = "Ping", "State","DesktopsRegistered"
$xaControllerHeaderWidths = "2", "2", "2"
$xaControllerTableWidth= 1200

<#foreach ($disk in $diskLettersControllers)
{
    $xaControllerHeaderNames += "$($disk)Freespace"
    $xaControllerHeaderWidths += "4"
}#>

$xaControllerHeaderNames +=  "AvgCPU", "MemUsg"
$xaControllerHeaderWidths +=    "4", "4"
  

#Header for Table "MachineCatalogs" Get-BrokerCatalog
$catalogHeaderName = "Catalog Details"
$catalogHeaderNames = "AssignedToUser", "AssignedToDG", "NotToUserAssigned","ProvisioningType", "AllocationType", "MinimumFunctionalLevel"
$catalogWidths = "4", "8", "8", "8", "8", "4"
$catalogTablewidth = 900
  



#Header for Table "DeliveryGroups" Get-BrokerDesktopGroup
$assigmentFirstHeaderName = "DeliveryGroup Details"
$vAssigmentHeaderNames = "PublishedName","DesktopKind", "SessionSupport", "TotalMachines","DesktopsAvailable","DesktopsUnregistered", "DesktopsInUse","DesktopsFree", "MaintenanceMode", "MinimumFunctionalLevel"
$vAssigmentHeaderWidths = "4", "4", "4", "4", "4", "4", "4", "2", "2", "2"
$assigmentTableWidth = 900
  


#Header for Table "XenApp Checks" Get-BrokerMachine
$xenappFirstHeaderName = "XenApp-Server HealthCheck"
$xenappHeaderNames = "CatalogName", "DeliveryGroup", "Serverload", "Ping", "MaintMode","Uptime", "RegState", "VDAVersion"
$xenappHeaderWidths = "4", "4", "4", "4", "4", "4", "4", "4"


<#foreach ($disk in $diskLettersWorkers)
{
    $xenappHeaderNames += "$($disk)Freespace"
    $xenappHeaderWidths += "4"
}#>

if ($showConnectedXenAppUsers -eq "1") 
    { 

$xenappHeaderNames += "AvgCPU", "MemUsg", "ActiveSessions"
$xenappHeaderWidths +="4", "4",   "4"
    }
else
    { 
$xenappHeaderNames += "AvgCPU", "MemUsg", "ActiveSessions"
$xenappHeaderWidths +="4", "4", "4"

    }

$xenapptablewidth = 1200



#Header for Table "services Checks of Controller" 
$controllerServiceFirstHeaderName = "DDC Server Services Check"
$controllerServiceHeaderNames = "Ping","CitrixADIdentityService","CitrixBrokerService","CitrixAnalytics","CitrixConfigurationLoggingService","CitrixConfigurationService","CitrixDelegatedAdministrationService", "CitrixEnvironmentTestService","CitrixHostService","CitrixMachineCreationService","CitrixMonitorService" ,"CitrixStorefrontService" ,"CitrixStorefrontPrivilegedAdministrationService"                                                                                                   
$controllerServiceHeaderWidths = "4","4", "4", "4", "4", "4", "4", "4", "4", "4", "4", "4" , "4"
$controllerServiceTableWidth = 600
  

#Header for Table "services Checks of XenApp servers" 
$xenappServiceFirstHeaderName = "XenApp-Servers Services Check"
$xenappServiceHeaderNames = "Ping","CitrixDesktopService", "CitrixDeviceRedirectorService", "CitrixDiagnosticFacilityCOMServer", "CitrixEncryptionService","CitrixEndUserExperiencingMonitoring", "CitrixGroupPolicyEngine", "CitrixHDXMediaStreamforFlashService", "CitrixPrintManagerService","CitrixProfileManagement"
$xenappServiceHeaderWidths = "4","4", "4", "4", "4", "4", "4", "4", "4", "4"
$xenappServiceTableWidth = 600


#Header for Table "services Checks of PVS" 
$pvsServiceFirstHeaderName = "PVS Server Service Check"
$pvsServiceHeaderNames = "Ping","CitrixPVSBOOTPService", "CitrixPVSPXEService", "CitrixPVSRamdiskServer", "CitrixPVSSoapServer", "CitrixPVSStreamService","CitrixPVSTFTPService", "CitrixPVSTwoStageBootService", "CitrixSubscriptionsStore"
$pvsServiceHeaderWidths = "4","4", "4", "4", "4", "4", "4", "4", "4"
$pvsServiceTableWidth = 600                                                                                                            
   


#==============================================================================================
#log function for logging all activities
function LogMe() 
{

Param(
[parameter(Mandatory = $true, ValueFromPipeline = $true)] $logEntry,
[switch]$display,
[switch]$error,
[switch]$warning,
[switch]$progress
)
  
if ($error) { $logEntry = "[ERROR] $logEntry" ; Write-Host "$logEntry" -Foregroundcolor Red }
elseif ($warning) { Write-Warning "$logEntry" ; $logEntry = "[WARNING] $logEntry" }
elseif ($progress) { Write-Host "$logEntry" -Foregroundcolor Green }
elseif ($display) { Write-Host "$logEntry" }
 
$logEntry | Out-File $logFile -Append -Force
}
  
#==============================================================================================
#For checking Ping Status
function Ping([string]$hostname, [int]$timeout = 200)
 {
$ping = new-object System.Net.NetworkInformation.Ping #creates a ping object
try { $result = $ping.send($hostname, $timeout).Status.ToString() }
catch { $result = "Failure" }
return $result
}
#==============================================================================================
# The function will check the processor counter and check for the CPU usage. Takes an average CPU usage for 1 seconds. It check the current CPU usage for 1 secs.
Function CheckCpuUsage() 
param ($hostname)
Try { #old # $cpuUsage=(get-counter -ComputerName $hostname -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 5 -ErrorAction Stop | select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average
    #old#$cpuUsage = [math]::round($cpuUsage, 1); return $cpuUsage
        $cpuusage=Get-WmiObject -ComputerName $hostname -Class Win32_processor | Measure-object -Property LoadPercentage -Average | Select -ExpandProperty Average
        return $cpuUsage
} Catch { "Error returned while checking the CPU usage. Reason Might be: RPC Server Unavailable, Maintenance Mode is ON, Ping Unsuccesful, Variable Issue " | LogMe -error; return 101 } 
}
#============================================================================================== 
# The function check the memory usage and report the usage value in percentage
Function CheckMemoryUsage() 
param ($hostname)
    Try 
{   $systemInfo = (Get-WmiObject -computername $hostname -Class Win32_OperatingSystem -ErrorAction Stop | Select-Object TotalVisibleMemorySize, FreePhysicalMemory)
    $totalRAM = $systemInfo.TotalVisibleMemorySize/1MB 
    $freeRAM = $systemInfo.FreePhysicalMemory/1MB 
    $usedRAM = $totalRAM - $freeRAM 
    $ramPercentUsed = ($usedRAM / $totalRAM) * 100 
    $ramPercentUsed = [math]::round($ramPercentUsed, 2);
    return $ramPercentUsed
} Catch { "Error returned while checking the Memory usage. Reason Might be: RPC Server Unavailable, Maintenance Mode is ON, Ping Unsuccesful, Variable Issue " | LogMe -error; return 101 } 
}
#==============================================================================================

# The function check the HardDrive usage and report the usage value in percentage and free space
Function CheckHardDiskUsage() 
param ($hostname, $deviceID)
    Try 
{   
    $harddisk = $null
$harddisk = Get-WmiObject Win32_LogicalDisk -ComputerName $hostname -Filter "DeviceID='$deviceID'" -ErrorAction Stop | Select-Object Size,FreeSpace
        if ($harddisk -ne $null)
{
$diskTotalSize = $harddisk.Size 
        $diskFreeSpace = $harddisk.FreeSpace 
        $frSpace=[Math]::Round(($diskFreeSpace/1073741824),2)
$percentageDS = (($diskFreeSpace / $diskTotalSize ) * 100); $percentageDS = [math]::round($percentageDS, 2)
Add-Member -InputObject $harddisk -MemberType NoteProperty -Name PercentageDS -Value $percentageDS
Add-Member -InputObject $harddisk -MemberType NoteProperty -Name frSpace -Value $frSpace
    return $harddisk
} Catch { "Error returned while checking the Hard Disk usage. Reason Might be: RPC Server Unavailable, Maintenance Mode is ON, Ping Unsuccesful, Variable Issue " | LogMe -error; return $null } 
}

#==============================================================================================
# ==============================================================================================
Function ToHumanReadable()
{
  param($timespan)
  
  If ($timespan.TotalHours -lt 1) {
    return $timespan.Minutes + "minutes"
  }

  $sb = New-Object System.Text.StringBuilder
  If ($timespan.Days -gt 0) {
    [void]$sb.Append($timespan.Days)
    [void]$sb.Append(" days")
    [void]$sb.Append(", ")    
  }
  If ($timespan.Hours -gt 0) {
    [void]$sb.Append($timespan.Hours)
    [void]$sb.Append(" hours")
  }
  If ($timespan.Minutes -gt 0) {
    [void]$sb.Append(" and ")
    [void]$sb.Append($timespan.Minutes)
    [void]$sb.Append(" minutes")
  }
  return $sb.ToString()
}
#==============================================================================================

#Function Writes HTML page header data 
Function writeHtmlHeader
{
param($title, $fileName)
$title = "GLOBAL Citrix 7.15 Report"
$date = $reportDate
$head = @"
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
<title>$title</title>
<STYLE TYPE="text/css">
<!--
td {
font-family: Tahoma;
font-size: 11px;
border-top: 1px solid #999999;
border-right: 1px solid #999999;
border-bottom: 1px solid #999999;
border-left: 1px solid #999999;
padding-top: 0px;
padding-right: 0px;
padding-bottom: 0px;
padding-left: 0px;
overflow: hidden;
}
body {
margin-left: 5px;
margin-top: 5px;
margin-right: 0px;
margin-bottom: 10px;
table {
table-layout:fixed;
border: thin solid #000000;
}
-->
</style>
</head>
<body>
<table width='1200'>
<tr bgcolor='#CCCCCC'>
<td colspan='7' height='48' align='center' valign="middle">
<font face='tahoma' color='#003399' size='4'>
<strong>$title - $date</strong></font>
</td>
</tr>
</table>
"@
$head | Out-File $filename
  }
# ==============================================================================================
#Function Writes HTML table header data 
Function writeTableHeader
{
param($fileName, $firstHeaderName, $headerNames, $headerWidths, $tableWidth)
$tableHeader = @"
  <p> </p>
<table width='$tableWidth'><tbody>
<tr bgcolor=#CCCCCC>
<td width='6%' align='center'><strong>$firstHeaderName</strong></td>
"@
  
$i = 0
while ($i -lt $headerNames.count) {
$headerName = $headerNames[$i]
$headerWidth = $headerWidths[$i]
$tableHeader += "<td width='" + $headerWidth + "%' align='center'><strong>$headerName</strong></td>"
$i++
}
  
$tableHeader += "</tr>"
  
$tableHeader | Out-File $fileName -append -Force
}
  
# ==============================================================================================
#Function Writes HTML table footer data 
Function writeTableFooter
{
param($fileName)
"</table><br/>"| Out-File $fileName -append -Force
}
  
#==============================================================================================
#Function Writes HTML data in report
Function writeData
{
param($data, $fileName, $headerNames)

$tableEntry  =""  
$data.Keys | sort | foreach {
$tableEntry += "<tr>"
$computerName = $_
$tableEntry += ("<td bgcolor='#CCCCCC' align=center><font color='#003399'>$computerName</font></td>")

$headerNames | foreach {

try {
if ($data.$computerName.$_[0] -eq "SUCCESS") { $bgcolor = "#387C44"; $fontColor = "#FFFFFF" }
elseif ($data.$computerName.$_[0] -eq "WARNING") { $bgcolor = "#FF7700"; $fontColor = "#FFFFFF" }
elseif ($data.$computerName.$_[0] -eq "ERROR") { $bgcolor = "#FF0000"; $fontColor = "#FFFFFF" }
else { $bgcolor = "#CCCCCC"; $fontColor = "#003399" }
$testResult = $data.$computerName.$_[1]
}
catch {
$bgcolor = "#CCCCCC"; $fontColor = "#003399"
$testResult = ""
}
$tableEntry += ("<td bgcolor='" + $bgcolor + "' align=center><font color='" + $fontColor + "'>$testResult</font></td>")
}
$tableEntry += "</tr>"
}
$tableEntry | Out-File $fileName -append -Force
}
  
# ==============================================================================================
#Function Writes HTML page footer data 
Function writeHtmlFooter
{
param($fileName)
@"
</table>
<table width='1200'>
<tr bgcolor='#CCCCCC'>
<td colspan='7' height='25' align='left'>
<font face='courier' color='#000000' size='2'>

<strong>Uptime Threshold: </strong> $maxUpTimeDays days <br>
<strong>Database: </strong> $dbInfo <br>
<strong>LicenseServerName: </strong> $lsname <strong>LicenseServerPort: </strong> $lsport <br>

</font>
</td>
</table>
</body>
</html>
"@ | Out-File $fileName -append -Force
}



# ==============================================================================================
<# Get information about user that set maintenance mode.
.DESCRIPTION
Over the Citrix XenDeesktop or XenApp log database, you can find the user that
set the maintenance mode of an worker.
This is version 1.0.
.PARAMETER AdminAddress
Specifies the address of the Delivery Controller to which the PowerShell module will connect. This can be provided as a host name or an IP address.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
.EXAMPLE
Get-CitrixMaintenanceInfo
Get the informations on an delivery controller with nedded credentials.
.EXAMPLE
Get-CitrixMaintenanceInfo -AdminAddress server.domain.tld -Credential (Get-Credential)
Use sever.domain.tld to get the log informations and use credentials.

#>
Function Get-CitrixMaintenanceInfo {
[CmdletBinding()]
[OutputType([System.Management.Automation.PSCustomObject])]
param
(
[Parameter(Mandatory = $false,
   ValueFromPipeline = $true,
   Position = 0)]
[System.String[]]$adminAddress = 'localhost',
[Parameter(Mandatory = $false,
   ValueFromPipeline = $true,
   Position = 1)]
[System.Management.Automation.PSCredential]$credential
) # Param
Try {
$psSessionParam = @{ }
If ($null -ne $credential) { $psSessionParam['Credential'] = $credential } #Splatting
If ($null -ne $adminAddress) { $psSessionParam['ComputerName'] = $adminAddress } #Splatting
# Create Session
$session = New-PSSession -ErrorAction Stop @psSessionParam
# Create script block for invoke command
$scriptBlock = {
if ((Get-PSSnapin "Get-PSSnapin Citrix.ConfigurationLogging.Admin.*" -ErrorAction silentlycontinue) -eq $null) {
try { Add-PSSnapin Citrix.ConfigurationLogging.Admin.* -ErrorAction Stop } 
                catch 
                {
                 $mailAlert ++ 
                 Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
                 write-error "Error Get-PSSnapin Citrix.ConfigurationLogging.Admin.* Powershell snapin"; Return 
                 }
} #If
$date = Get-Date
$startDate = $date.AddDays(-7) # Hard coded value for how many days back
$endDate = $date
# Command to get the informations from log
$logEntrys = Get-LogLowLevelOperation -MaxRecordCount 1000000 -Filter { StartTime -ge $startDate -and EndTime -le $endDate } | Where { $_.Details.PropertyName -eq 'MAINTENANCEMODE' } | Sort EndTime -Descending
# Build an object with the data for the output
[array]$arrMaintenance = @()
ForEach ($logEntry in $logEntrys) {
$tempObj = New-Object -TypeName psobject -Property @{
User = $logEntry.User
TargetName = $logEntry.Details.TargetName
NewValue = $logEntry.Details.NewValue
PreviousValue = $logEntry.Details.PreviousValue
StartTime = $logEntry.Details.StartTime
EndTime = $logEntry.Details.EndTime
} #TempObj
$arrMaintenance += $tempObj
} #ForEach
$arrMaintenance
} # ScriptBlock
# Run the script block with invoke-command, return the values and close the session
$maintLogs = Invoke-Command -Session $session -ScriptBlock $scriptBlock -ErrorAction Stop
Write-Output $maintLogs
Remove-PSSession -Session $session -ErrorAction SilentlyContinue
} Catch {
Write-Warning "Error occurs: $_"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
} # Try/Catch
}  Get-CitrixMaintenanceInfo



#==============================================================================================
rm $logFile -force -EA SilentlyContinue
rm $resultsHTM -force -EA SilentlyContinue
  
"#### Begin with Citrix XenApp HealthCheck ######################################################################" | LogMe -display -progress
  
" " | LogMe -display -progress

# get some farm infos, which will be presented in footer 
$dbInfo = Get-BrokerDBConnection -AdminAddress $adminAddress
$brokerSiteInfos = Get-BrokerSite
$lsname = $brokerSiteInfos.LicenseServerName
$lsport = $brokerSiteInfos.LicenseServerPort
$cLeasing = $brokerSiteInfos.ConnectionLeasingEnabled


# Log the loaded Citrix PS Snapins
(Get-PSSnapin "Citrix.*" -EA silentlycontinue).Name | ForEach {"PSSnapIn: " + $_ | LogMe -display -progress} 
  
#== Controller Check ============================================================================================
"Check Controllers #############################################################################" | LogMe -display -progress
  
" " | LogMe -display -progress
  
$controllerResults = @{}
$controllers = Get-BrokerController -AdminAddress $adminAddress

# Get first DDC version (should be all the same unless an upgrade is in progress)
$controllerVersion = $controllers[0].ControllerVersion
"Version: $controllerVersion " | LogMe -display -progress
  
if ($controllerVersion -lt 7 ) 
{
  "XenApp Version below 7.x ($controllerVersion) - only DesktopCheck will be performed" | LogMe -display -progress
  #$showXenAppTable = 0 #doesent work with XML variables
  Set-Variable -Name ShowXenAppTable -Value 0
}
 else 
  "XenApp Version above 7.x ($controllerVersion) - XenApp will be performed" | LogMe -display -progress
}

foreach ($controller in $controllers) 
{
$tests = @{}

#Name of $controller
$controllerDNS = $controller | %{ $_.DNSName 
}

"Controller: $controllerDNS" | LogMe -display -progress
  
#Ping $controller
$result = Ping $controllerDNS 100
if ($result -ne "SUCCESS") { $tests.Ping = "Error", $result 
$mailAlert++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe}
else { $tests.Ping = "SUCCESS", $result 

#Now when Ping is ok also check this:
  
#State of this controller
$controllerState = $controller | %{ $_.State }
"State: $controllerState" | LogMe -display -progress
if ($controllerState -ne "Active") { $tests.State = "ERROR", $controllerState 
$mailAlert++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}
else { $tests.State = "SUCCESS", $controllerState }
  
#DesktopsRegistered on this controller
$controllerDesktopsRegistered = $controller | %{ $_.DesktopsRegistered }
"Registered: $controllerDesktopsRegistered" | LogMe -display -progress
$tests.DesktopsRegistered = "NEUTRAL", $controllerDesktopsRegistered
  
#ActiveSiteServices on this controller
$activeSiteServices = $controller | %{ $_.ActiveSiteServices }
"ActiveSiteServices $activeSiteServices" | LogMe -display -progress
$tests.ActiveSiteServices = "NEUTRAL", $activeSiteServices


#==============================================================================================
#               CHECK CPU AND MEMORY USAGE 
#==============================================================================================

        # Check the AvgCPU value for 1 seconds
        $avgCPUval = CheckCpuUsage ($controllerDNS)
#$VDtests.LoadBalancingAlgorithm = "SUCCESS", "LB is set to BEST EFFORT"} 
        if( [int] $avgCPUval -lt 85) { "CPU usage is normal [ $avgCPUval % ]" | LogMe -display; $tests.AvgCPU = "SUCCESS", "$avgCPUval %" }
elseif([int] $avgCPUval -lt 95) { "CPU usage is medium [ $avgCPUval % ]" | LogMe -warning; $tests.AvgCPU = "WARNING", "$avgCPUval %" }   
elseif([int] $avgCPUval -lt 99) { "CPU usage is high [ $avgCPUval % ]" | LogMe -error; $tests.AvgCPU = "ERROR", "$avgCPUval %"
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" }
elseif([int] $avgCPUval -eq 101) { "CPU usage test failed" | LogMe -error; $tests.AvgCPU = "ERROR", "Err" 
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED"
}
        else { "CPU usage is Critical [ $avgCPUval % ]" | LogMe -error; $tests.AvgCPU = "ERROR", "$avgCPUval %"
        $mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" }   
$avgCPUval = 0

        # Check the Physical Memory usage       
        $usedMemory = CheckMemoryUsage ($controllerDNS)
        if( $usedMemory -lt 75) { "Memory usage is normal [ $usedMemory % ]" | LogMe -display; $tests.MemUsg = "SUCCESS", "$usedMemory %" }
elseif( [int] $usedMemory -lt 85) { "Memory usage is medium [ $usedMemory % ]" | LogMe -warning; $tests.MemUsg = "WARNING", "$usedMemory %" }   
elseif( [int] $usedMemory -lt 95) { "Memory usage is high [ $usedMemory % ]" | LogMe -error; $tests.MemUsg = "ERROR", "$usedMemory %"
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" }
elseif( [int] $usedMemory -eq 101) { "Memory usage test failed" | LogMe -error; $tests.MemUsg = "ERROR", "Err"
 $mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" }
        else { "Memory usage is Critical [ $usedMemory % ]" | LogMe -error; $tests.MemUsg = "ERROR", "$usedMemory %" 
        $mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED"}   
$usedMemory = 0  

        foreach ($disk in $diskLettersControllers)
        {
            # Check Disk Usage 
    $harddisk = CheckHardDiskUsage -hostname $controllerDNS -deviceID "$($disk):"
    if ($harddisk -ne $null) {
    $xaPercentageDS = $harddisk.PercentageDS
    $frSpace = $harddisk.frSpace
            If ( [int] $xaPercentageDS -gt 15) { "Disk Free is normal [ $xaPercentageDS % ]" | LogMe -display; $tests."$($disk)Freespace" = "SUCCESS", "$frSpace GB" } 
    ElseIf ([int] $xaPercentageDS -eq 0) { "Disk Free test failed" | LogMe -error; $tests."$($disk)Freespace" = "ERROR", "Err"
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" }
    ElseIf ([int] $xaPercentageDS -lt 5) { "Disk Free is Critical [ $xaPercentageDS % ]" | LogMe -error; $tests."$($disk)Freespace" = "ERROR", "$frSpace GB"
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" } 
    ElseIf ([int] $xaPercentageDS -lt 15) { "Disk Free is Low [ $xaPercentageDS % ]" | LogMe -warning; $tests."$($disk)Freespace" = "WARNING", "$frSpace GB" }     
            Else { "Disk Free is Critical [ $xaPercentageDS % ]" | LogMe -error; $tests."$($disk)Freespace" = "ERROR", "$frSpace GB" 
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED"}  
        
    $xaPercentageDS = 0
    $frSpace = 0
    $harddisk = $null
    }
        }
    # Check uptime (Query over WMI)
    $tests.WMI = "ERROR","Error"
    try { $wmi=Get-WmiObject -class Win32_OperatingSystem -computer $controllerDNS }
    catch { $wmi = $null
    $mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe }

    # Perform WMI related checks
    if ($wmi -ne $null) {
        $tests.WMI = "SUCCESS", "Success"
        $lbTime=$wmi.ConvertToDateTime($wmi.Lastbootuptime)
        [TimeSpan]$uptime=New-TimeSpan $lbTime $(get-date)

        if ($uptime.days -lt $minUpTimeDaysDDC){
            "reboot warning, last reboot: {0:D}" -f $lbTime | LogMe -display -warning
            $tests.Uptime = "WARNING", (ToHumanReadable($uptime))
        }
        else { $tests.Uptime = "SUCCESS", (ToHumanReadable($uptime)) }
    }
    else { "WMI connection failed - check WMI for corruption" | LogMe -display -error
    $mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe }
}


  
" --- " | LogMe -display -progress
#Fill $tests into array
$controllerResults.$controllerDNS = $tests
}

#== Catalog Check ============================================================================================
"Check Catalog #################################################################################" | LogMe -display -progress
" " | LogMe -display -progress
  
$catalogResults = @{}
$catalogs = Get-BrokerCatalog -AdminAddress $adminAddress
  
foreach ($catalog in $catalogs) 
{
  $tests = @{}
  
  #Name of MachineCatalog
  $catalogName = $catalog | %{ $_.Name }
  "Catalog: $catalogName" | LogMe -display -progress

  if ($excludedCatalogs -contains $catalogName) 
  {
    "Excluded Catalog, skipping" | LogMe -display -progress
  } else {
    #CatalogAssignedCount
    $catalogAssignedCount = $catalog | %{ $_.AssignedCount }
    "Assigned: $catalogAssignedCount" | LogMe -display -progress
    $tests.AssignedToUser = "NEUTRAL", $catalogAssignedCount
  
    #CatalogUnassignedCount
    $catalogUnAssignedCount = $catalog | %{ $_.UnassignedCount }
    "Unassigned: $catalogUnAssignedCount" | LogMe -display -progress
    $tests.NotToUserAssigned = "NEUTRAL", $catalogUnAssignedCount
  
    # Assigned to DeliveryGroup
    $catalogUsedCountCount = $catalog | %{ $_.UsedCount }
    "Used: $catalogUsedCountCount" | LogMe -display -progress
    $tests.AssignedToDG = "NEUTRAL", $catalogUsedCountCount

    #MinimumFunctionalLevel
$minimumFunctionalLevel = $catalog | %{ $_.MinimumFunctionalLevel }
"MinimumFunctionalLevel: $minimumFunctionalLevel" | LogMe -display -progress
    $tests.MinimumFunctionalLevel = "NEUTRAL", $minimumFunctionalLevel
  
     #ProvisioningType
     $catalogProvisioningType = $catalog | %{ $_.ProvisioningType }
     "ProvisioningType: $catalogProvisioningType" | LogMe -display -progress
     $tests.ProvisioningType = "NEUTRAL", $catalogProvisioningType
  
     #AllocationType
     $catalogAllocationType = $catalog | %{ $_.AllocationType }
     "AllocationType: $catalogAllocationType" | LogMe -display -progress
     $tests.AllocationType = "NEUTRAL", $catalogAllocationType
  
    "", ""
    $catalogResults.$catalogName = $tests
  }  
  " --- " | LogMe -display -progress
}
  
#==========================================================================================================================
#DeliveryGroups Check TABLE
#==========================================================================================================================
"Check Assigments #############################################################################" | LogMe -display -progress
  
" " | LogMe -display -progress
  
$assigmentsResults = @{}
$assigments = Get-BrokerDesktopGroup -AdminAddress $adminAddress
  
foreach ($assigment in $assigments) 
{
  $tests = @{}
  
  #Name of DeliveryGroup
  $deliveryGroup = $assigment | %{ $_.Name }
  "DeliveryGroup: $deliveryGroup" | LogMe -display -progress
  
  if ($excludedCatalogs -contains $deliveryGroup) 
  {
    "Excluded Delivery Group, skipping" | LogMe -display -progress
  } 
  else
  {
    #PublishedName
    $assigmentDesktopPublishedName = $assigment | %{ $_.PublishedName }
    "PublishedName: $assigmentDesktopPublishedName" | LogMe -display -progress
    $tests.PublishedName = "NEUTRAL", $assigmentDesktopPublishedName
  
    #DesktopsTotal
    $totalDesktops = $assigment | %{ $_.TotalDesktops }
    "DesktopsAvailable: $totalDesktops" | LogMe -display -progress
    $tests.TotalMachines = "NEUTRAL", $totalDesktops
  
    #DesktopsAvailable
    $assigmentDesktopsAvailable = $assigment | %{ $_.DesktopsAvailable }
    "DesktopsAvailable: $assigmentDesktopsAvailable" | LogMe -display -progress
    $tests.DesktopsAvailable = "NEUTRAL", $assigmentDesktopsAvailable
  
    #DesktopKind
    $assigmentDesktopsKind = $assigment | %{ $_.DesktopKind }
    "DesktopKind: $assigmentDesktopsKind" | LogMe -display -progress
    $tests.DesktopKind = "NEUTRAL", $assigmentDesktopsKind
#SessionSupport
$sessionSupport = $assigment | %{ $_.SessionSupport }
"SessionSupport: $sessionSupport" | LogMe -display -progress
    $tests.SessionSupport = "NEUTRAL", $sessionSupport
#ShutdownAfterUse
$shutdownDesktopsAfterUse = $assigment | %{ $_.ShutdownDesktopsAfterUse }
"ShutdownDesktopsAfterUse: $shutdownDesktopsAfterUse" | LogMe -display -progress
    
if ($sessionSupport -eq "MultiSession" -and $shutdownDesktopsAfterUse -eq "$true" ) 
    { 
$tests.ShutdownAfterUse = "ERROR", $shutdownDesktopsAfterUse
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED"
}
else
    { 
$tests.ShutdownAfterUse = "NEUTRAL", $shutdownDesktopsAfterUse
}

    #MinimumFunctionalLevel
$minimumFunctionalLevel = $assigment | %{ $_.MinimumFunctionalLevel }
"MinimumFunctionalLevel: $minimumFunctionalLevel" | LogMe -display -progress
    $tests.MinimumFunctionalLevel = "NEUTRAL", $minimumFunctionalLevel
if ($sessionSupport -eq "MultiSession" ) 
    { 
$tests.DesktopsFree = "NEUTRAL", "N/A"
$tests.DesktopsInUse = "NEUTRAL", "N/A"
}
    else 
    { 
#DesktopsInUse
$assigmentDesktopsInUse = $assigment | %{ $_.DesktopsInUse }
"DesktopsInUse: $assigmentDesktopsInUse" | LogMe -display -progress
$tests.DesktopsInUse = "NEUTRAL", $assigmentDesktopsInUse
#DesktopFree
$assigmentDesktopsFree = $assigmentDesktopsAvailable - $assigmentDesktopsInUse
"DesktopsFree: $assigmentDesktopsFree" | LogMe -display -progress
  
if ($assigmentDesktopsKind -eq "shared") 
            {
    if ($assigmentDesktopsFree -gt 0 ) 
                {
"DesktopsFree < 1 ! ($assigmentDesktopsFree)" | LogMe -display -progress
$tests.DesktopsFree = "SUCCESS", $assigmentDesktopsFree
    } 
                elseif ($assigmentDesktopsFree -lt 0 ) 
                {
"DesktopsFree < 1 ! ($assigmentDesktopsFree)" | LogMe -display -progress
$tests.DesktopsFree = "SUCCESS", "N/A"
    } 
                else 
                {
$tests.DesktopsFree = "WARNING", $assigmentDesktopsFree
"DesktopsFree > 0 ! ($assigmentDesktopsFree)" | LogMe -display -progress
    }
            else
            {
   $tests.DesktopsFree = "NEUTRAL", "N/A"
}
}
  
    #inMaintenanceMode check
    $assigmentDesktopsinMaintenanceMode = $assigment | %{ $_.inMaintenanceMode }
    "inMaintenanceMode: $assigmentDesktopsinMaintenanceMode" | LogMe -display -progress
    if ($assigmentDesktopsinMaintenanceMode) 
        { 
        $tests.MaintenanceMode = "WARNING", "ON" 
        }
    else
        {
         $tests.MaintenanceMode = "SUCCESS", "OFF" 
        }
  
    #DesktopsUnregistered
    $assigmentDesktopsUnregistered = $assigment | %{ $_.DesktopsUnregistered }
    "DesktopsUnregistered: $assigmentDesktopsUnregistered" | LogMe -display -progress    
    if ($assigmentDesktopsUnregistered -gt 0 ) 
    {
      "DesktopsUnregistered > 0 ! ($assigmentDesktopsUnregistered)" | LogMe -display -progress
      $tests.DesktopsUnregistered = "WARNING", $assigmentDesktopsUnregistered
    } 
    else 
    {
      $tests.DesktopsUnregistered = "SUCCESS", $assigmentDesktopsUnregistered
      "DesktopsUnregistered <= 0 ! ($assigmentDesktopsUnregistered)" | LogMe -display -progress
    }
        
    #Fill $tests into array
    $assigmentsResults.$deliveryGroup = $tests
  }
  " --- " | LogMe -display -progress
}
  
####################################################################################################################################################################
################################################################################################################################################################### 
                                                   # ======= XenApp Health Check ========#
####################################################################################################################################################################
####################################################################################################################################################################
"Check XenApp Servers ####################################################################################" | LogMe -display -progress
" " | LogMe -display -progress
  
# Check XenApp only if $showXenAppTable is 1
if($showXenAppTable -eq 1 ) 
{
$allXenAppResults = @{}
$xenappServiceResult =@{}  
$controllerServiceResult =@{}
$pvsServiceResult = @{} 

$xaMachines = Get-BrokerMachine -MaxRecordCount $maxMachines -AdminAddress $adminAddress | Where-Object {$_.SessionSupport -eq "MultiSession" -and @(compare $_.tags $ExcludedTags -IncludeEqual | ? {$_.sideindicator -eq '=='}).count -eq 0}

$maintenance = Get-CitrixMaintenanceInfo -AdminAddress $adminAddress
  
foreach ($xamachine in $xaMachines) 
{
$tests = @{}
  
# Column Name of Machine
$machineDNS = $xamachine | %{ $_.DNSName }
"Machine: $machineDNS" | LogMe -display -progress
  
# Column CatalogNameName
$catalogName = $xamachine | %{ $_.CatalogName }
"Catalog: $catalogName" | LogMe -display -progress
$tests.CatalogName = "NEUTRAL", $catalogName
  
# Ping Machine
$result = Ping $machineDNS 100
if ($result -eq "SUCCESS") 
{
$tests.Ping = "SUCCESS", $result
  
#==============================================================================================
# Column Uptime (Query over WMI - only if Ping successfull)
$tests.WMI = "ERROR","Error"
$job = Start-Job -ScriptBlock $wmiOSBlock -ArgumentList $machineDNS
$wmi = Wait-job $job -Timeout 15 | Receive-Job

# Perform WMI related checks
if ($wmi -ne $null) 
{
$tests.WMI = "SUCCESS", "Success"
$lbTime=[Management.ManagementDateTimeConverter]::ToDateTime($wmi.Lastbootuptime)
[TimeSpan]$uptime=New-TimeSpan $lbTime $(get-date)

if ($uptime.days -gt $maxUpTimeDays)
    {
"reboot warning, last reboot: {0:D}" -f $lbTime | LogMe -display -warning
$tests.Uptime = "WARNING", $uptime.days
    else 
    {
$tests.Uptime = "SUCCESS", $uptime.days
}
else
 {
"WMI connection failed - check WMI for corruption" | LogMe -display -error
stop-job $job
$mailAlert ++
 Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
 }
 #=================
  

  
}
else { $tests.Ping = "Error", $result
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" }
#END of Ping-Section
  
# Column Serverload
$serverload = $xamachine | %{ $_.LoadIndex }
"Serverload: $serverload" | LogMe -display -progress
if ($serverload -ge $loadIndexError) { $tests.Serverload = "ERROR", $serverload 
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe}
elseif ($serverload -ge $loadIndexWarning) { $tests.Serverload = "WARNING", $serverload }
else { $tests.Serverload = "SUCCESS", $serverload }
  
# Column MaintMode
$maintMode = $xamachine | %{ $_.InMaintenanceMode }
"MaintenanceMode: $maintMode" | LogMe -display -progress
if ($maintMode) 
    { 
$objMaintenance = $maintenance | Where { $_.TargetName.ToUpper() -eq $xamachine.MachineName.ToUpper() } | Select -First 1
If ($null -ne $objMaintenance){$maintenanceModeOn = ("ON, " + $objMaintenance.User)} 
    Else {$maintenanceModeOn = "ON"}

"MaintenanceModeInfo: $maintenanceModeOn" | LogMe -display -progress
$tests.MaintMode = "WARNING", $maintenanceModeOn
$errorVDI = $errorVDI + 1
    }
else { $tests.MaintMode = "SUCCESS", "OFF" }
  
# Column RegState
$regState = $xamachine | %{ $_.RegistrationState }
"State: $regState" | LogMe -display -progress
  
if ($regState -ne "Registered") { $tests.RegState = "ERROR", $regState 
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe}
else { $tests.RegState = "SUCCESS", $regState }

# Column VDAVersion AgentVersion
$vdaVersion = $xamachine | %{ $_.AgentVersion }
"VDAVersion: $vdaVersion" | LogMe -display -progress
$tests.VDAVersion = "NEUTRAL", $vdaVersion

# Column ActiveSessions
$activeSessions = $xamachine | %{ $_.SessionCount }
"Active Sessions: $activeSessions" | LogMe -display -progress
$tests.ActiveSessions = "NEUTRAL", $activeSessions

<# Column ConnectedUsers
$connectedUsers = $xamachine | %{ $_.AssociatedUserNames }
"Connected users: $connectedUsers" | LogMe -display -progress
$tests.ConnectedUsers = "NEUTRAL", $connectedUsers#>
  
# Column DeliveryGroup
$deliveryGroup = $xamachine | %{ $_.DesktopGroupName }
"DeliveryGroup: $deliveryGroup" | LogMe -display -progress
$tests.DeliveryGroup = "NEUTRAL", $deliveryGroup


#==============================================================================================
#               CHECK CPU AND MEMORY USAGE 
#==============================================================================================

        # Check the AvgCPU value for 1 seconds
        $xaAvgCPUval = CheckCpuUsage ($machineDNS)
#$VDtests.LoadBalancingAlgorithm = "SUCCESS", "LB is set to BEST EFFORT"} 
        if( [int] $xaAvgCPUval -lt 85) { "CPU usage is normal [ $xaAvgCPUval % ]" | LogMe -display; $tests.AvgCPU = "SUCCESS", "$xaAvgCPUval %" }
elseif([int] $xaAvgCPUval -lt 95) { "CPU usage is medium [ $xaAvgCPUval % ]" | LogMe -warning; $tests.AvgCPU = "WARNING", "$xaAvgCPUval %" }   
elseif([int] $xaAvgCPUval -lt 99) { "CPU usage is high [ $xaAvgCPUval % ]" | LogMe -error; $tests.AvgCPU = "ERROR", "$xaAvgCPUval %"
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED" }
elseif([int] $xaAvgCPUval -eq 101) { "CPU usage test failed" | LogMe -error; $tests.AvgCPU = "ERROR", "Err" 
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED"}
        else { "CPU usage is Critical [ $xaAvgCPUval % ]" | LogMe -error; $tests.AvgCPU = "ERROR", "$xaAvgCPUval %" 
        $mailAlert ++ 
        Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe}   
$xaAvgCPUval = 0

        # Check the Physical Memory usage       
        [int] $xaUsedMemory = CheckMemoryUsage ($machineDNS)
        if( [int] $xaUsedMemory -lt 75) { "Memory usage is normal [ $xaUsedMemory % ]" | LogMe -display; $tests.MemUsg = "SUCCESS", "$xaUsedMemory %" }
elseif( [int] $xaUsedMemory -lt 85) { "Memory usage is medium [ $xaUsedMemory % ]" | LogMe -warning; $tests.MemUsg = "WARNING", "$xaUsedMemory %" }   
elseif( [int] $xaUsedMemory -lt 95) { "Memory usage is high [ $xaUsedMemory % ]" | LogMe -error; $tests.MemUsg = "ERROR", "$xaUsedMemory %" 
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED"}
elseif( [int] $xaUsedMemory -eq 101) { "Memory usage test failed" | LogMe -error; $tests.MemUsg = "ERROR", "Err" 
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED"}
        else { "Memory usage is Critical [ $xaUsedMemory % ]" | LogMe -error; $tests.MemUsg = "ERROR", "$xaUsedMemory %" 
        $mailAlert ++ 
        Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe}   
$xaUsedMemory = 0  

        <#foreach ($disk in $diskLettersWorkers)
        {
            # Check Disk Usage 
            $harddisk = CheckHardDiskUsage -hostname $machineDNS -deviceID "$($disk):"
    if ($harddisk -ne $null) 
            {
    $xaPercentageDS = $harddisk.PercentageDS
    $frSpace = $harddisk.frSpace

    If ( [int] $xaPercentageDS -gt 15) { "Disk Free is normal [ $xaPercentageDS % ]" | LogMe -display; $tests."$($disk)Freespace" = "SUCCESS", "$frSpace GB" } 
    ElseIf ([int] $xaPercentageDS -eq 0) { "Disk Free test failed" | LogMe -error; $tests.CFreespace = "ERROR", "Err" 
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe}
    ElseIf ([int] $xaPercentageDS -lt 5) { "Disk Free is Critical [ $xaPercentageDS % ]" | LogMe -error; $tests."$($disk)Freespace" = "ERROR", "$frSpace GB" 
$mailAlert ++ 
    Write-host "MAILALERT VARIABLE INCREMENTED"} 
    ElseIf ([int] $xaPercentageDS -lt 15) { "Disk Free is Low [ $xaPercentageDS % ]" | LogMe -warning; $tests."$($disk)Freespace" = "WARNING", "$frSpace GB" }     
    Else { "Disk Free is Critical [ $xaPercentageDS % ]" | LogMe -error; $tests."$($disk)Freespace" = "ERROR", "$frSpace GB" 
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe}
    $xaPercentageDS = 0
    $frSpace = 0
    $harddisk = $null
    }
        }#>

  
" --- " | LogMe -display -progress
  
# Check to see if the server is in an excluded folder path
if ($excludedCatalogs -contains $catalogName) { "$machineDNS in excluded folder - skipping" | LogMe -display -progress }
else { $allXenAppResults.$machineDNS = $tests }
}
  

  # Check services for Xenapp servers
  foreach ($xamachine in $xaMachines) 
{
 $xenappService= @{}
  
# Column Name of Machine
$machineDNS = $xamachine | %{ $_.DNSName }
"Machine: $machineDNS" | LogMe -display -progress
  
# Ping Machine
$result = Ping $machineDNS 100
if ($result -eq "SUCCESS") 
{
$xenappService.Ping = "SUCCESS", $result
  
 $servicesWMI = Get-WmiObject -Class Win32_Service -Computer $machineDNS

if(($servicesWMI | ? { $_.StartName -match "NetworkService" } | Where-Object {($_.DisplayName -match "Citrix Desktop Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Desktop Service..OK..." | LogMe
$xenappService.CitrixDesktopService = "SUCCESS","Success"
}
else
{
"Citrix Desktop Service.. ISSUE" | LogMe -display -error
$xenappService.CitrixDesktopService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}
  

if(($servicesWMI | ? { $_.StartName -match "NetworkService" } | Where-Object {($_.DisplayName -match "Citrix Audio Redirection Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Audio Redirection Service.. OK..." | LogMe
$xenappService.CitrixAudioRedirectionService = "SUCCESS","Success"
}
else
{
"Citrix Audio Redirection Service.. ISSUE ..." | LogMe -display -error
$xenappService.CitrixAudioRedirectionService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "NetworkService" } | Where-Object {($_.DisplayName -match "Citrix Diagnostic Facility COM Server") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Diagnostic Facility COM Server Service..OK..." | LogMe
$xenappService.CitrixDiagnosticFacilityCOMServer = "SUCCESS","Success"
}
else
{
"Citrix Diagnostic Facility COM Server Service.. ISSUE" | LogMe -display -error
$xenappService.CitrixDiagnosticFacilityCOMServer = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}



if(($servicesWMI | ? { $_.StartName -match "LocalService" } | Where-Object {($_.DisplayName -match "Citrix Device Redirector Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Device Redirector Service..OK..." | LogMe
$xenappService.CitrixDeviceRedirectorService = "SUCCESS","Success"
}
else
{
"Citrix Device Redirector Service.. ISSUE" | LogMe -display -error
$xenappService.CitrixDeviceRedirectorService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "LocalService" } | Where-Object {($_.DisplayName -match "Citrix Encryption Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Encryption Service..OK..." | LogMe
$xenappService.CitrixEncryptionService = "SUCCESS","Success"
}
else
{
"Citrix Encryption Service..ISSUE" | LogMe -display -error
$xenappService.CitrixEncryptionService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "LocalService" } | Where-Object {($_.DisplayName -match "Citrix End User Experiencing Monitoring") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix End User Experiencing Monitoring Service.. OK..." | LogMe
$xenappService.CitrixEndUserExperiencingMonitoring = "SUCCESS","Success"
}
else
{
"Citrix End User Experiencing Monitoring Service.. ISSUE" | LogMe -display -error
$xenappService.CitrixEndUserExperiencingMonitoring = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}



if(($servicesWMI | ? { $_.StartName -match "LocalService" } | Where-Object {($_.Name -match "CtxFlashSvc") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix HDX MediaStream for Flash Service..OK..." | LogMe
$xenappService.CitrixHDXMediaStreamforFlashService = "SUCCESS","Success"
}
else
{
"Citrix HDX MediaStream for Flash Service..ISSUE" | LogMe -display -error
$xenappService.CitrixHDXMediaStreamforFlashService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}



if(($servicesWMI | ? { $_.StartName -match "LocalService" } | Where-Object {($_.DisplayName -match "Citrix Print Manager Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Print Manager Service..OK..." | LogMe
$xenappService.CitrixPrintManagerService = "SUCCESS","Success"
}
else
{
"Citrix Print Manager Service..ISSUE" | LogMe -display -error
$xenappService.CitrixPrintManagerService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}

 

if(($servicesWMI | ? { $_.StartName -match "LocalSystem" } | Where-Object {($_.DisplayName -match "Citrix Group Policy Engine") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Group Policy Engine Service.. OK..." | LogMe
$xenappService.CitrixGroupPolicyEngine = "SUCCESS","Success"
}
else
{
"Citrix Group Policy Engine Service..ISSUE" | LogMe -display -error
$xenappService.CitrixGroupPolicyEngine = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "LocalSystem" } | Where-Object {($_.DisplayName -match "Citrix Profile Management") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Profile Management Service.. OK..." | LogMe
$xenappService.CitrixProfileManagement  = "SUCCESS","Success"
}
else
{
"Citrix Profile Management Service..ISSUE" | LogMe -display -error
$xenappService.CitrixProfileManagement  = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "LocalSystem" } | Where-Object {($_.DisplayName -match "Citrix PVS Device Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix PVS Device Service..OK..." | LogMe
$xenappService.CitrixPVSDeviceService  = "SUCCESS","Success"
}
else
{
"Citrix PVS Device Service..ISSUE" | LogMe -display -error
$xenappService.CitrixPVSDeviceService  = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


}
else { $xenappService.Ping = "Error", $result
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe }
#END of Ping-Section
  

  
" --- " | LogMe -display -progress
  
$xenappServiceResult.$machineDNS = $xenappService
}
  

}
else { "XenApp Check skipped because ShowXenAppTable = 0 or Farm is < V7.x " | LogMe -display -progress }
  

#####################################################################################################
##########################################################################################################
###############################################################################################
#====Service check for controller====================
foreach ($controller in $controllers) 
{

$controllerService = @{} 

#Name of $controller
$controllerDNS = $controller | %{ $_.DNSName 
}

"Controller: $controllerDNS" | LogMe -display -progress
  
# Ping Machine
$result = Ping $controllerDNS 100
if ($result -eq "SUCCESS") 
{
$controllerService.Ping = "SUCCESS", $result
  
  
# Check services for Xenapp servers

$servicesWMI = Get-WmiObject -Class Win32_Service -Computer $controllerDNS

if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix AD Identity Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixADIdentityService..OK..." | LogMe
$controllerService.CitrixADIdentityService = "SUCCESS","Success"
}
else
{
"CitrixADIdentityService.. ISSUE" | LogMe -display -error
$controllerService.CitrixADIdentityService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "NetworkService" } | Where-Object {($_.DisplayName -match "Citrix Broker Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Broker Service..OK..." | LogMe
$controllerService.CitrixBrokerService = "SUCCESS","Success"
}
else
{
"Citrix Broker Service.. ISSUE" | LogMe -display -error
$controllerService.CitrixBrokerService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}

if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Analytics") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixAnalytics..OK..." | LogMe
$controllerService.CitrixAnalytics = "SUCCESS","Success"
}
else
{
"CitrixAnalytics.. ISSUE" | LogMe -display -error
$controllerService.CitrixAnalytics = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Configuration Logging Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixConfigurationLoggingService..OK..." | LogMe 
$controllerService.CitrixConfigurationLoggingService = "SUCCESS","Success"
}
else
{
"CitrixAnalytics.. ISSUE" | LogMe -display -error
$controllerService.CitrixConfigurationLoggingService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Configuration Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixConfigurationService..OK..." | LogMe
$controllerService.CitrixConfigurationService = "SUCCESS","Success"
}
else
{
"CitrixConfigurationService.. ISSUE" | LogMe -display -error
$controllerService.CitrixConfigurationService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}

if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Delegated Administration Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixDelegatedAdministrationService..OK..." | LogMe
$controllerService.CitrixDelegatedAdministrationService = "SUCCESS","Success"
}
else
{
"CitrixDelegatedAdministrationService.. ISSUE" | LogMe -display -error
$controllerService.CitrixDelegatedAdministrationService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "NetworkService" } | Where-Object {($_.DisplayName -match "Citrix Diagnostic Facility COM Server") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixDiagnosticFacilityCOMServer..OK..." | LogMe
$controllerService.CitrixDiagnosticFacilityCOMServer = "SUCCESS","Success"
}
else
{
"CitrixDiagnosticFacilityCOMServere.. ISSUE" | LogMe -display -error
$controllerService.CitrixDiagnosticFacilityCOMServer = "ERROR","Error"
$mailAlert ++
 Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}

if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Environment Test Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixEnvironmentTestService..OK..." | LogMe
$controllerService.CitrixEnvironmentTestService = "SUCCESS","Success"
}
else
{
"CitrixEnvironmentTestService.. ISSUE" | LogMe -display -error
$controllerService.CitrixEnvironmentTestService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Host Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixHostService..OK..." | LogMe
$controllerService.CitrixHostService = "SUCCESS","Success"
}
else
{
"CitrixHostService.. ISSUE" | LogMe -display -error
$controllerService.CitrixHostService = "ERROR","Error"
$mailAlert ++
 Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Machine Creation Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixMachineCreationService..OK..." | LogMe
$controllerService.CitrixMachineCreationService = "SUCCESS","Success"
}
else
{
"CitrixMachineCreationService.. ISSUE" | LogMe -display -error
$controllerService.CitrixMachineCreationService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Monitor Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixMonitorService..OK..." | LogMe
$controllerService.CitrixMonitorService = "SUCCESS","Success"
}
else
{
"CitrixMonitorService.. ISSUE" | LogMe -display -error
$controllerService.CitrixMonitorService = "ERROR","Error"
$mailAlert ++
 Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Storefront Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixStorefrontService..OK..." | LogMe
$controllerService.CitrixStorefrontService = "SUCCESS","Success"
}
else
{
"CitrixStorefrontService.. ISSUE" | LogMe -display -error
$controllerService.CitrixStorefrontService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}


if(($servicesWMI | ? { $_.StartName -match "SYSTEM" } | Where-Object {($_.DisplayName -match "Citrix Storefront Privileged Administration Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"Citrix Storefront Privileged Administration Service..OK..." | LogMe
$controllerService.CitrixStorefrontPrivilegedAdministrationService = "SUCCESS","Success"
}
else
{
"Citrix Storefront Privileged Administration Service.. ISSUE" | LogMe -display -error
$controllerService.CitrixStorefrontPrivilegedAdministrationService = "ERROR","Error"
$mailAlert ++
 Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}



}
else { $controllerService.Ping = "Error", $result 
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe}
#END of Ping-Section
  

  
" --- " | LogMe -display -progress
  

$controllerServiceResult.$controllerDNS = $controllerService
  }


#====Service check for PVS Server====================
  
 # foreach($pvsServer in $pvsServers)
  #{
  $pvsService = @{} 

#Name of $controller
#$pvsDNS = $pvsServer | %{ $_.DNSName }

"PVS Server: $pvsServer" | LogMe -display -progress
  
# Ping Machine
$result = Ping $pvsServer 100
if ($result -eq "SUCCESS") 
{
$pvsService.Ping = "SUCCESS", $result
  
  
# Check services for PVS server

$pvsServicesWMI = Get-WmiObject -Class Win32_Service -Computer $pvsServer

if(($pvsServicesWMI | ? { $_.StartName -match "LocalService" } | Where-Object {($_.DisplayName -match "Citrix PVS BOOTP Service") -and ($_.State -match "Stopped") -and ($_.StartMode -match "Manual") }))
{
"CitrixPVSBOOTPService..OK..." | LogMe
$pvsService.CitrixPVSBOOTPService = "SUCCESS","Success"
}
else
{
"CitrixPVSBOOTPService.. ISSUE" | LogMe -display -error
$pvsService.CitrixPVSBOOTPService = "ERROR","Error"
$mailAlert ++
 Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}

if(($pvsServicesWMI | ? { $_.StartName -match "LocalService" } | Where-Object {($_.DisplayName -match "Citrix PVS PXE Service") -and ($_.State -match "Stopped") -and ($_.StartMode -match "Disabled") }))
{
"CitrixPVSPXEService..OK..." | LogMe
$pvsService.CitrixPVSPXEService = "SUCCESS","Success"
}
else
{
"CitrixPVSPXEService.. ISSUE" | LogMe -display -error
$pvsService.CitrixPVSPXEService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}

if(($pvsServicesWMI | ? { $_.StartName -match "sa_ctxpvs" } | Where-Object {($_.DisplayName -match "Citrix PVS Ramdisk Server") -and ($_.State -match "Stopped") -and ($_.StartMode -match "Manual") }))
{
"CitrixPVSRamdiskServer Service..OK..." | LogMe
$pvsService.CitrixPVSRamdiskServer = "SUCCESS","Success"
}
else
{
"CitrixPVSRamdiskServer Service.. ISSUE" | LogMe -display -error
$pvsService.CitrixPVSRamdiskServer = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}

if(($pvsServicesWMI | ? { $_.StartName -match "sa_ctxpvs" } | Where-Object {($_.DisplayName -match "Citrix PVS Soap Server") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixPVSSoapServer Service..OK..." | LogMe
$pvsService.CitrixPVSSoapServer = "SUCCESS","Success"
}
else
{
"CitrixPVSSoapServer Service.. ISSUE" | LogMe -display -error
$pvsService.CitrixPVSSoapServer = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe
}

if(($pvsServicesWMI | ? { $_.StartName -match "sa_ctxpvs" } | Where-Object {($_.DisplayName -match "Citrix PVS Stream Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixPVSStream Service..OK..." | LogMe
$pvsService.CitrixPVSStreamService = "SUCCESS","Success"
}
else
{
"CitrixPVSStream Service.. ISSUE" | LogMe -display -error
$pvsService.CitrixPVSStreamService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe | LogMe
}

if(($pvsServicesWMI | ? { $_.StartName -match "LocalService" } | Where-Object {($_.DisplayName -match "Citrix PVS TFTP Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixPVSTFTPService..OK..." | LogMe
$pvsService.CitrixPVSTFTPService = "SUCCESS","Success"
}
else
{
"CitrixPVSTFTPService.. ISSUE" | LogMe -display -error
$pvsService.CitrixPVSStreamService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe | LogMe
}

if(($pvsServicesWMI | ? { $_.StartName -match "LocalService" } | Where-Object {($_.DisplayName -match "Citrix PVS Two-Stage Boot Service") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixPVSTwo-StageBootService..OK..." | LogMe
$pvsService.CitrixPVSTwoStageBootService = "SUCCESS","Success"
}
else
{
"CitrixPVSTwo-StageBootService.. ISSUE" | LogMe -display -error
$pvsService.CitrixPVSTwoStageBootService = "ERROR","Error"
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe | LogMe
}

if(($pvsServicesWMI | ? { $_.StartName -match "Network Service" } | Where-Object {($_.DisplayName -match "Citrix Subscriptions Store") -and ($_.State -match "Running") -and ($_.StartMode -match "Auto") }))
{
"CitrixSubscriptionsStore..OK..." | LogMe
$pvsService.CitrixSubscriptionsStore = "SUCCESS","Success"
}
else
{
"CitrixSubscriptionsStore.. ISSUE" | LogMe -display -error
$pvsService.CitrixSubscriptionsStore = "ERROR","Error"
$mailAlert ++
 Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe | LogMe
}
  

}
else { $pvsService.Ping = "Error", $result
$mailAlert ++ 
Write-host "MAILALERT VARIABLE INCREMENTED" | LogMe | LogMe }
#END of Ping-Section

" --- " | LogMe -display -progress
  

$pvsServiceResult.$pvsServer = $pvsService  

#}
####################### Check END ####################################################################################" | LogMe -display -progress
# ======= Write all results to an html file =================================================
# Add Version of XenDesktop to EnvironmentName

$xaMajor, $xaMinor = $controllerVersion.Split(".")[0..1]
$xaVersion = "$xaMajor.$xaMinor"
$environmentNameOut = "$environmentName $xaVersion"

$emailSubject = ("GLOBAL $environmentNameOut Daily Health Check Report - " + $reportDate)

Write-Host ("Saving results to html report: " + $resultsHTM)
writeHtmlHeader "$environmentNameOut Monitoring Report" $resultsHTM
  
# Write Table with the Controllers

writeTableHeader $resultsHTM $xaControllerFirstHeaderName $xaControllerHeaderNames $xaControllerHeaderWidths $xaControllerTableWidth
$controllerResults | sort-object -property xaControllerFirstheaderName | %{ writeData $controllerResults $resultsHTM $xaControllerHeaderNames }
writeTableFooter $resultsHTM

# Write Table with the Catalogs

writeTableHeader $resultsHTM $catalogHeaderName $catalogHeaderNames $catalogWidths $catalogTablewidth
$catalogResults | %{ writeData $catalogResults $resultsHTM $catalogHeaderNames}
writeTableFooter $resultsHTM
   
# Write Table with the Assignments (Delivery Groups)

writeTableHeader $resultsHTM $assigmentFirstHeaderName $vAssigmentHeaderNames $vAssigmentHeaderWidths $assigmentTableWidth
$assigmentsResults | sort-object -property replState | %{ writeData $assigmentsResults $resultsHTM $vAssigmentHeaderNames }
writeTableFooter $resultsHTM 

# Write Table with all XenApp Servers
if ($showXenAppTable -eq 1 ) {

writeTableHeader $resultsHTM $xenappFirstHeaderName $xenappHeaderNames $xenappHeaderWidths $xenapptablewidth
$allXenAppResults | sort-object -property CatalogName | %{ writeData $allXenAppResults $resultsHTM $xenappHeaderNames }
writeTableFooter $resultsHTM
}
else { "No XenApp output in HTML " | LogMe -display -progress }

#Write Table with all services of Xenapp

writeTableHeader $resultsHTM $xenappServiceFirstHeaderName $xenappServiceHeaderNames $xenappServiceHeaderWidths $xenappServiceTableWidth
$xenappServiceResult | sort-object -property Services | %{ writeData $xenappServiceResult $resultsHTM $xenappServiceHeaderNames }
writeTableFooter $resultsHTM
  
#Write Table with all services of Controller Server

writeTableHeader $resultsHTM $controllerServiceFirstHeaderName $controllerServiceHeaderNames $controllerServiceHeaderWidths $controllerServiceTableWidth
$controllerServiceResult | sort-object -property controllerService | %{ writeData $controllerServiceResult $resultsHTM $controllerServiceHeaderNames }
writeTableFooter $resultsHTM 
 
<#Write Table with all services of Controller Server

writeTableHeader $resultsHTM $pvsServiceFirstHeaderName $pvsServiceHeaderNames $pvsServiceHeaderWidths $pvsServiceTableWidth
$pvsServiceResult | sort-object -property pvsService | %{ writeData $pvsServiceResult $resultsHTM $pvsServiceHeaderNames }
writeTableFooter $resultsHTM #>

 writeHtmlFooter $resultsHTM


####################################################################################################################################
####################################################################################################################################
#SendMail Logic

####################################################################################################################################
####################################################################################################################################



if ($mailAlert -ne 0)
{

#send email
$emailMessage = New-Object System.Net.Mail.MailMessage

$emailMessage.Body = (gc $resultsHTM) | Out-String

Send-MailMessage -From $emailFrom -To $emailTo -Cc $emailCc -Subject $emailSubject -BodyAsHtml $emailMessage.Body -SmtpServer $smtpServer


Write-Host "Some Error in script" 
}
else
{Write-Host "No errors in script"
}


if ($currentTime -eq $triggerHour )
{

#send email
$emailMessage = New-Object System.Net.Mail.MailMessage

$emailMessage.Body = (gc $resultsHTM) | Out-String

Send-MailMessage -From $emailFrom -To $emailTo -Cc $emailCc -Subject $emailSubject -BodyAsHtml $emailMessage.Body -SmtpServer $smtpServer


Write-Host "Mail sent on specified triggerHour" 
}
else
{
}




#########################################################################
#####################AUR Bot Reporting Code( Do not Delete) #####################
#########################################################################
$emailBotEndTimeOfScript = Get-Date -UFormat "%Y-%m-%d %H:%M:%S"
$emailBotBody = 
"##AUR_START##
AutomationName:$emailBotFileNameExtention
EndPointName:$endpointName
StartTime:$emailBotStartTimeOfScript
DurationToFinish:$emailBotEndTimeOfScript
StatusOfRun:Success
ExecutionID:$emailBotExecutionID
InputType:Email
##AUR_END##"

Send-MailMessage -Body $emailBotBody -From $emailBotFromAddress -to $emailBotToAddress -Subject $emailBotSubject -SmtpServer $emailBotSmtpAddress

##########################################################################
#########################EventLog Section#################################
##########################################################################
#This makes an entry in the event log with the $emailBotBody to track as Information
$returnSuccess = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).`
IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if ($returnSuccess)
{

## Write in EventLog #########
New-EventLog –LogName Application –Source “NonRBAScript” -ErrorAction Ignore 
Write-EventLog -LogName "Application" -Source "NonRBAScript" -EventID 2266 `
-EntryType Information -Message "$emailBotBody" `
-Category 1 -RawData 10,20
$var=Test-Path "C:\Automation_log"
## Write in Log Directory #######
if($var -match "False")
{
mkdir "C:\Automation_log"
}
$path="C:\Automation_log"
$userName=whoami
$scriptName=$MyInvocation.MyCommand.Name
$date=get-date
 
"$($userName)   $($scriptName)   $($date)"  >> "$path\script_execution_log.txt"
}
else
{
Write-Host "You need to be a administrator to log the details in EventLog" -ForegroundColor Red
######## AUR BOT Code end ##############################################
#####################################################################





No comments:

Post a Comment