Use PowerShell PowerCLI to show VMs created in the last 14 days from vCenter

Problem:

How do I get an emailed report to show VMs that have been created in the last 14 days from vCenter?

Solution:

Run the below script:

Import-Module VMware.VimAutomation.Core

Connect-VIServer servername

Get-VIEvent -maxsamples 10000 -Start (Get-Date).AddDays(14) |
where {$_.Gettype().Name-eq "VmCreatedEvent" -or $_.Gettype().Name-eq "VmBeingClonedEvent" -or $_.Gettype().Name-eq "VmBeingDeployedEvent"} |
Sort CreatedTime -Descending |
Select CreatedTime, UserName,FullformattedMessage, @{ Name="CPU"; Expression={(Get-VM -Name $_.Vm.Name).NumCPU}}, @{ Name="MemoryGB"; Expression={(Get-VM -Name $_.Vm.Name).MemoryGB}} |
export-csv c:\Scripts\VMsCreated.csv -nti


$emailSmtpServer = "10.16.15.02"
$emailSmtpServerPort = "25"

$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "vCenter <infrastructurereports@domain.com>"
$emailMessage.To.Add( "infrastructureteam@domain.com" )
$emailMessage.Subject = "Virtual Machines Created in Woking DC Production Cluster"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = @"
<p>Please review the attached reports and identify VMs created for this period.</p>
"@

$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$attachment = "c:\Scripts\VMsCreated.csv"
$emailMessage.Attachments.Add( $attachment ) 
$SMTPClient.Send( $emailMessage ) 

Leave a Reply

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