Virtual Machine expiration date PowerCLI script

From time to time a new VM request pops out but what if this specific VM is only temporary? Well, it would be great if you could put an expiration date on this VM just like a carton of milk, don’t you think?

In order to get a daily report for all your expired VM you need to do the following:

Create an additional VM annotation value called “Expiration Date”. You will also have to fill up the actual expiration date for this VM in a “MM/dd/yyyy” Get-Date PowerShell command format, for example: 06/04/2012

The Script:

[sourcecode language=”powershell”]
$Server = "Your vCenter Server"
$SMTPserver = "Your Mail Server"
$From = "Sender@domain.com"
$To = "Recipient@domain.com"
# ————————————————————
Connect-VIServer $Server
$Date = Get-Date -Format MM/dd/yyyy

# Format html report
$HTMLReport = @"
<style type=’text/css’>
.heading {
color:#357EC7;
font-size:12.0pt;
font-weight:700;
font-family:Verdana, sans-serif;
text-align:left;
vertical-align:middle;
height:30.0pt;
width:416pt
}
.colnames {
color:white;
font-size:8.0pt;
font-weight:700;
font-family:Tahoma, sans-serif;
text-align:center;
vertical-align:middle;
border:.5pt solid windowtext;
background:#1569C7;
}
.text {
color:black;
font-size:8.0pt;
font-family:Arial;
text-align:center;
vertical-align:middle;
border:.5pt solid windowtext;
background:#FFFFFF;
}
</style>
<table border=0 cellpadding=0 cellspacing=0 width=555
style=’border-collapse:collapse;table-layout:auto;width:00pt’>
<tr style=’height:15.0pt’>
<th colspan=5 height=40 width=555>
vSphere Expired VM Daily Report</th>
</tr>
<tr>
<th>Expired Virtual Machine Name</th>
</tr>
"@

$VMList = Get-VM | Get-Annotation | Where-Object {$_.Value -eq $Date}| select -ExpandProperty AnnotatedEntity
$ExpiredVM = $VMList | select Name

ForEach ($ExpiredVM in $VMList)
{
if( $ExpiredVM -ne $null)
{
$HTMLReport = $HTMLReport +
"<tr><td class=’text’>" + $ExpiredVM + "</td></tr>"
}
}

$HTMLReport = $HTMLReport + "</table>"

# Send email
$Subject = "vSphere Expired Virtual Machine Daily Report"
$emailbody = $HTMLReport
$Mailer = New-Object Net.Mail.SMTPclient($SMTPserver)
$msg = New-Object Net.Mail.MailMessage($From, $To, $Subject, $emailbody)
$msg.IsBodyHTML = $true
$Mailer.send($msg)
[/sourcecode]

So, filling up the new annotation field and running the script will result you getting this cool daily expired VM report so that way you will not forget deleting a VM with one year expiration date 🙂

Good luck !

Be the first to comment

Leave a Reply