Monday, May 23, 2011

Citrix: PowerShell script to check XenApp offline servers and send only incremental records

Existing scenario:
The PowerShell script checks for offline servers and stores the record in a log file. The script is scheduled to run on every 1 hour. It overwrites the existing log file and then send the log file by email.

Requirement:
The script will check for existing offline server(s) record in the log file and then send only newly added records (delta changes) by email.

Add-PSSnapin citrix.XenApp.Commands

$Log_File="C:\OfflineServers.log"
$DeltaFile = "C:\OfflineServers-Changed.log"

# Executing the command to check for Offline Server and stores in a log file
$ExistingList = Get-Content $Log_File
$NewList = QFARM /OFFLINE

# This defines newly added entries, ignoring removed entries
$DeltaList = Compare-Object $ExistingList $NewList | 
  Where-Object { $_.SideIndicator -eq '=>' } |
  Select-Object -ExpandProperty InputObject

# Write that to a temp file for the attachment
$DeltaList | Out-File $DeltaFile -Encoding ASCII

# Save the complete list
$NewList | Out-File $log_file -Encoding ASCII

#Sending Email
$smtpServer = "<SMTP Server Name>"
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($DeltaFile)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "<From Email Address>"
$msg.To.Add("<To Email Address>")
$msg.Subject = "Offline Servers"
$msg.Body = "List of Offline Servers"
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()

No comments:

Post a Comment