$taskNameTemplate = 'Scheduled snapshot of $($vm.Name)'$snapNameTemplate = 'Snapshot of $($vm.Name)'
$emailAddr = 'lucd@lucd.info'
$snapMemory = $false
$snapQuiesce = $true
$report = @()
$si = Get-View ServiceInstance
$scheduledTaskManager = Get-View $si.Content.ScheduledTaskManager
# CSV layout
# Name,Description,DateTime
# vm1,'Snapshot of VM1','06/15/2020 12:30'
# vm2,'Snapshot of VM2','06/16/2020 13:30'
Import-Csv -Path .\vmnames.csv -UseCulture -PipelineVariable row |
ForEach-Object -Process {
# Get the target VM
$vm = Get-VM -Name $row.Name
# Remove an existing scheduled task for the VM
$scheduledTaskManager.RetrieveEntityScheduledTask($vm.ExtensionData.MoRef) |
ForEach-Object -Process {
Get-View -Id $_ | where{$_.Info.Name -match 'Snapshot of'} |
ForEach-Object -Process {
$_.RemoveScheduledTask()
}
}
# Create a new scheduled task
$spec = New-Object VMware.Vim.ScheduledTaskSpec
$spec.Name = $ExecutionContext.InvokeCommand.ExpandString($taskNameTemplate)
$spec.Description = "Take a snapshot of $($vm.Name)"
$spec.Enabled = $true
$spec.Notification = $emailAddr
$spec.Scheduler = New-Object VMware.Vim.OnceTaskScheduler
$spec.Scheduler.runat = [DateTime]$row.DateTime
$spec.Action = New-Object VMware.Vim.MethodAction
$spec.Action.Name = "CreateSnapshot_Task"
$snapName = $ExecutionContext.InvokeCommand.ExpandString($snapNameTemplate)
$snapDescription = $row.Description
@($snapName,$row.Description,$snapMemory,$snapQuiesce) | %{
$arg = New-Object VMware.Vim.MethodActionArgument
$arg.Value = $_
$spec.Action.Argument += $arg
}
$report += New-Object -TypeName PSObject -Property ([ordered]@{
Server = $vm.Name
Description = "Take a snapshot of $($vm.Name)"
'Scheduled Date' = [DateTime]$row.DateTime
})
$scheduledTaskManager.CreateObjectScheduledTask($vm.ExtensionData.MoRef, $spec)
}
$sMail = @{
From = 'script@my.domain'
To = 'me@my.domain'
Subject = 'Scheduled Task Report'
SmtpServer = 'mail.my.domain'
BodyAsHtml = $true
Body = $report | ConvertTo-Html | Out-String
}
Send-MailMessage @sMail