I have cobbled together a automated shutdown script below which reads a text file and shuts a list of specific VM's down. It sort of works however if in the event the script was unable able to gracefully shut a VM down (i.e VMtools was not running/installed) I need the script to provide a exit code and send an email alert. I think I have found a bit of suitable code (highlighted in red below) which can achieve this however I'm not 100% about how to implement it. I wondered if someone could kindly show me an example so I can try to learn from it.
# ==============================================================================================
# Parameters
param (
[string]$VMsToShutDownUp
)
# ================================================================================================
# ==============================================================================================
# Varibles
$waittime= 60 #Seconds
#Email varibles
$From = "vCenter@blah.net"
$To = "luke@blah.net"
$Cc = "luke@blah.net"
#$Attachment = "C:\temp\Some random file.txt"
$Subject = "!! TEST DMAT Report TEST !!"
$BodySuccess = "Valid VM parameters have been supplied by ControlM and the Shutdown command has been executed"
$BodyFailure1 = "Control M has supplied an invalid VM name Parameter or the VM does not exist within the infrastructure"
$SMTPServer = "192.168.0.101"
$SMTPPort = "25"
# Add the vmware snapin for powershell
Add-PSSnapin VMware.VimAutomation.Core
# Establish Connection
Connect-VIServer -Server 127.0.0.1 -User administrator@blah -Password blah
# ----- Check if the passed parameters are empty or not
#
if(!$VMsToShutDownUp)
{
Write-Output "You havent supplied the name of a VM that exists within the infrastructure"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $BodyFailure1 -SmtpServer $SMTPServer -port $SMTPPort
}
else
{
#
# ----- Split the passed parameters and for each value perform task
#
$VMsToShutDownUp.Split(',') | ForEach {
Get-VM $_ | Shutdown-VMGuest -Confirm:$false
Write-host "Pausing for $waittime seconds to allow VMs to shutdown cleanly. VMware tools must be installed and running for this to work"
$waittime
do {
#Check the power status
$MyVM = Get-VM -Name myvirtualmachinename
$status = $MyVM.PowerState
}until($status -eq "PoweredOff")
}
Exit 1
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $BodySuccess -SmtpServer $SMTPServer -port $SMTPPort
}
}
Give this a shot (two choices)
#If you want to create an array of failed vm's
#before the loop create an empty array
$FailedList = @()
if (! (Get-VM $_ | Shutdown-VMGuest -Confirm:$false)) {
Write-Output "The VM did not shutdown"
$FailedList += $MyVM
}
#or if you just want to send an email per VM
if (! (Get-VM $_ | Shutdown-VMGuest -Confirm:$false)) {
Write-Output "The VM did not shutdown"
#Put your Send-MailMessage code here
}