I work with a lot of scheduled tasks. Typically, these tasks run powershell scripts from the Windows Task Scheduler. However, when working with simple VMware tasks (like creating snapshots right before a maintenance window) I like to use the Scheduled Tasks feature from right inside vCenter. The other day I thought it would be interesting if I had a PowerShell function that I could run to create these snapshot tasks. The first step in this process is to figure out what tasks we already have…and understand where some of these properties are located using PowerCLI.
The following two functions can be used to get information on Scheduled Tasks inside vCenter. The first function Get-VIScheduledTasks will simply return a list of all scheduled tasks that exist in a vCenter environment. I picked out a handful of properties that I figured would be needed and return those by default, casting the date/time values into local time. If you need all of the properties (the native .Net view of the Scheduled Task Info objects) you can include the parameter -Full and all of the properties will be returned.
[cc lang=”powershell”]
Function Get-VIScheduledTasks {
PARAM ( [switch]$Full )
if ($Full) {
# Note: When returning the full View of each Scheduled Task, all date times are in UTC
(Get-View ScheduledTaskManager).ScheduledTask | %{ (Get-View $_).Info }
} else {
# By default, lets only return common headers and convert all date/times to local values
(Get-View ScheduledTaskManager).ScheduledTask | %{ (Get-View $_ -Property Info).Info } |
Select-Object Name, Description, Enabled, Notification, LastModifiedUser, State, Entity,
@{N=”EntityName”;E={ (Get-View $_.Entity -Property Name).Name }},
@{N=”LastModifiedTime”;E={$_.LastModifiedTime.ToLocalTime()}},
@{N=”NextRunTime”;E={$_.NextRunTime.ToLocalTime()}},
@{N=”PrevRunTime”;E={$_.LastModifiedTime.ToLocalTime()}},
@{N=”ActionName”;E={$_.Action.Name}}
}
}
[/cc]
This next function calls above function, but only returns the tasks whose action is “CreateSnapshot_Task”
[cc lang = “Powershell”]
Function Get-VMScheduledSnapshots {
Get-VIScheduledTasks | ?{$_.ActionName -eq ‘CreateSnapshot_Task’} |
Select-Object @{N=”VMName”;E={$_.EntityName}}, Name, NextRunTime, Notification
}
[/cc]
Sample usage would be:
# To find all tasks that failed to execute last run
Get-VIScheduledTasks | ?{$_.State -ne 'success'}
# To find all snapshots that are not scheduled to run again:
Get-VMScheduledSnapshots | ?{$_.NextRunTime -eq $null}
I hope you find these functions useful. Be sure to check out the next post – on creating scheduled snapshots with PowerCLI!