Here is a script to get tasks (historic tasks not just current) and also the events associated with that task.
This is very handy for auditing or troubleshooting.
The task collection part of the script I found on LucD blog at https://www.lucd.info/tag/get-task/
Basically this will get all tasks and events for a specific time frame. It will then loop through each task and get the events associated with that task (the ChainID)
$hours = 4 # Number of hours to go back
$ResultFile = "Tasks_and_Events.csv" # file name for the csv
$Result = @()
$start = (Get-Date).AddHours(-$hours)
$tasknumber = 999 # WindowSize for task collector
$Evnts = get-vievent -Start ((get-date).addhours(-$hours)) -Finish (get-date)
$taskMgr = Get-View TaskManager
# building the task filter
$taskFilter = New-Object VMware.Vim.TaskFilterSpec
$taskFilter.Time = New-Object VMware.Vim.TaskFilterSpecByTime
$taskFilter.Time.beginTime = $start
$taskFilter.Time.timeType = "startedTime"
$taskCollector = Get-View ($taskMgr.CreateCollectorForTasks($taskFilter))
# get 999($tasknumber of tasks from the taskCollector
$tasks = $taskCollector.ReadNextTasks($tasknumber)
while($tasks)
{
foreach($task in $tasks)
{
# create an object populated with task data
$tmpObj = New-Object PSObject -Property @{
Type = "Task"
target = $task.EntityName
TaskName = $task.DescriptionId
Start = $task.StartTime
Finish = $task.CompleteTime
Result = $task.State
User = $task.Reason.UserName
ChainID = $task.EventChainId
ID = ""
}
$Result += $tmpObj
# get events associated with this tast (ChainID)
$ChainEvnts = $Evnts | where{$_.chainID -eq $task.EventChainId}
foreach($ChainEvnt in $ChainEvnts)
{
# create an object populated with Event data
$tmpObj = New-Object PSObject -Property @{
Type = "Event"
target = ""
TaskName = $ChainEvnt.FullFormattedMessage
Start = $ChainEvnt.CreatedTime
Finish = ""
Result = ""
User = $ChainEvnt.UserName
ChainID = $ChainEvnt.ChainId
ID = $ChainEvnt.key
}
$Result += $tmpObj
}
}
# get the next 999 tasks. if this returns 0 (null) the while loop will end
$tasks = $taskCollector.ReadNextTasks($tasknumber)
} # end of while loop
# By default 32 task collectors are allowed. Destroy this task collector.
$taskCollector.DestroyCollector()
$Result | Export-Csv $ResultFile -NoTypeInformation