Get VMware vCenter Scheduled Tasks with PowerCLI

PowerCLI logoVMware vSphere PowerCLI is missing cmdlets to work with VMware vCenter Scheduled Tasks. In a series of blog posts I will show you some PowerShell advanced functions that you can use to work with vCenter Scheduled Tasks. The first function is Get-VCScheduledTask. You can use this function to retrieve one or more scheduled tasks from your vCenter Server.

The Get-VCScheduledTask function

function Get-VCScheduledTask {
<#
  .SYNOPSIS
    Retrieves the scheduled tasks on a vCenter Server.

  .DESCRIPTION
    Retrieves the scheduled tasks on a vCenter Server.

  .PARAMETER  Name
    Specify the name of the scheduled tasks you want to retrieve. If no value is
    given to this parameter, the command returns all the scheduled tasks.

  .PARAMETER  Server
    Specify the vCenter server to apply the command on. If no value is given to
    this parameter, the command runs on the server currently specified in the
    $DefaultVIServers variable.

  .EXAMPLE
    PS C:\> Get-VCScheduledTask -Server vCenter
    Retrieves all the scheduled tasks for the vCenter server named vCenter.

  .EXAMPLE
    PS C:\> Get-VCScheduledTask -Name "*Update Manager*"
    Retrieves all the VMware vSphere Update Manager scheduled tasks.

  .INPUTS
    System.String

  .OUTPUTS
    PSCustomObject

  .NOTES
    Author:  Robert van den Nieuwendijk
    Date:    17-1-2013
    Version: 1.0

  .LINK
    https://rvdnieuwendijk.com/
    

#>

  [CmdletBinding()]
  [OutputType([PSObject])]
  
  # Parameter definitions
  param([parameter(position=0)][string[]]$Name = "*",
        [parameter(position=1)][string[]]$Server = "*"
  )

  # Loop through the servers
  foreach ($SingleServer in $Server) {
    # Loop through the scheduled task names
    foreach ($SingleName in $Name) {
      # Create the parameterset for the Get-View cmdlet
      $GetViewParameterSet = @{
        Id = "ServiceInstance"
       } 
      if ($SingleServer)
      {
        $GetViewParameterSet += @{
          Server = $SingleServer
        }
      }  

      # Get the ScheduledTaskManager objects
      $ServiceInstance = Get-View @GetViewParameterSet
      $ScheduledTaskManager = $ServiceInstance |
        ForEach-Object {
          if ($_)
          {
            Get-View -Id $_.Content.ScheduledTaskManager
          }
        }
	
      # Get the scheduled tasks
      if ($ScheduledTaskManager) {
        Get-View -Id ($ScheduledTaskManager |
          Select -ExpandProperty ScheduledTask |
          Sort-Object -Unique) |
        Where-Object {
          $_.Info.Name -like $SingleName -and $_.Client.ServiceUrl.Split('/')[2].Split(':')[0] -like $SingleServer
        } |
        ForEach-Object {
          if ($_)
          {
            $ScheduledTask = $_

            # Find the server
            $VIServer = $global:DefaultVIServers |
              Where-Object {
                $_.Name -eq $ScheduledTask.Client.ServiceUrl.Split('/')[2].Split(':')[0]
              }
			
            # Create the output objects
            New-Object -TypeName PSObject -Property @{
              Name = $ScheduledTask.Info.Name
              Description = $ScheduledTask.Info.Description
              Action = $ScheduledTask.Info.Action
              EntityId = $ScheduledTask.Info.Entity
              Entity = $ScheduledTask.Info.Entity |
                Get-VIObjectByVIView -Server $VIServer
              Enabled = $ScheduledTask.Info.Enabled
              Notification = $ScheduledTask.Info.Notification
              State = $ScheduledTask.Info.State
              Progress = $ScheduledTask.Info.Progress
              LastModifiedTime = $ScheduledTask.Info.LastModifiedTime
              LastModifiedUser = $ScheduledTask.Info.LastModifiedUser
              NextRunTime = $ScheduledTask.Info.NextRunTime
              PrevRunTime = $ScheduledTask.Info.PrevRunTime
              Scheduler = $ScheduledTask.Info.Scheduler
              ExtensionData = $ScheduledTask
              Id = $ScheduledTask.MoRef
              Uid = "/VIServer=$($VIServer.User)@$($ScheduledTask.Client.ServiceUrl.Split('/')[2])/ScheduledTask=$($ScheduledTask.MoRef)/"
              Client = $ScheduledTask.Client
            } |
            Select-Object -Property Name,Description,Action,EntityId,Entity,Enabled,
              Notification,State,Progress,LastModifiedTime,LastModifiedUser,
              NextRunTime,PrevRunTime,Scheduler,ExtensionData,Id,Uid,Client
          }
        }
      }
    }
  }
}

Listing 1. The Get-VCScheduledTask function to retrieve VMware vCenter Scheduled tasks.

Annotations

Line 47-48: Both parameters are defined as [string[]]. That means that you can specify an array as the value of the parameter.

Line 55-64: A PowerShell technique called splatting is used to create the parameter set of the Get-View cmdlet used in line 67.

Line 67: The GetViewParameterSet variable is used as a parameter to the Get-View cmdlet. Notice that it is used as @GetViewParameterSet without a $ sign.

Line 117-119: The output of the New-Object cmdlet on line 96-116 can have it properties in an unsorted order. The Select-Object cmdlet orders the properties.

Sample output

The objects that the Get-VCScheduledTask function returns look like the objects that the PowerCLI Get-* cmdlets return. The objects have a Name, ExtensionData, Id, Uid and Client property.

PowerCLI C:\users\robert> Get-VCScheduledtask


Name             : VMware vCenter Update Manager Update Download
Description      : A pre-defined scheduled task to download software patch definitions.
Action           : VMware.Vim.CreateTaskAction
EntityId         : Folder-group-d1
Entity           : Datacenters
Enabled          : True
Notification     :
State            : success
Progress         :
LastModifiedTime : 6-11-2012 14:25:44
LastModifiedUser : com.vmware.vcIntegrity
NextRunTime      : 18-1-2013 03:10:00
PrevRunTime      : 17-1-2013 03:10:00
Scheduler        : VMware.Vim.DailyTaskScheduler
ExtensionData    : VMware.Vim.ScheduledTask
Id               : ScheduledTask-schedule-101
Uid              : /VIServer=rvdnieuwendijk\robert@vcenter:443/ScheduledTask=ScheduledTask-schedule-101/
Client           : VMware.Vim.VimClient

Name             : VMware vCenter Update Manager Check Notification
Description      : A pre-defined scheduled task to check update notifications.
Action           : VMware.Vim.CreateTaskAction
EntityId         : Folder-group-d1
Entity           : Datacenters
Enabled          : True
Notification     :
State            : success
Progress         :
LastModifiedTime : 6-11-2012 14:25:45
LastModifiedUser : com.vmware.vcIntegrity
NextRunTime      : 17-1-2013 20:04:00
PrevRunTime      : 17-1-2013 19:04:00
Scheduler        : VMware.Vim.HourlyTaskScheduler
ExtensionData    : VMware.Vim.ScheduledTask
Id               : ScheduledTask-schedule-102
Uid              : /VIServer=rvdnieuwendijk\robert@vcenter:443/ScheduledTask=ScheduledTask-schedule-102/
Client           : VMware.Vim.VimClient

Name             : Power on storage-test
Description      :
Action           : VMware.Vim.MethodAction
EntityId         : VirtualMachine-vm-109
Entity           : storage-test
Enabled          : True
Notification     :
State            : success
Progress         :
LastModifiedTime : 3-1-2013 14:03:00
LastModifiedUser : rvdnieuwendijk\robert
NextRunTime      :
PrevRunTime      : 5-1-2013 15:02:00
Scheduler        : VMware.Vim.OnceTaskScheduler
ExtensionData    : VMware.Vim.ScheduledTask
Id               : ScheduledTask-schedule-201
Uid              : /VIServer=rvdnieuwendijk\robert@vcenter:443/ScheduledTask=ScheduledTask-schedule-201/
Client           : VMware.Vim.VimClient



PowerCLI C:\users\robert>

Output 1. Sample output of the Get-VCscheduledTask function.

Have fun with scheduled tasks!

About Robert van den Nieuwendijk
Robert van den Nieuwendijk is a freelance senior systems engineer with over 30 years of experience in the IT industry. He focusses on VMware vCloud Suite and Microsoft Windows Server. He tries to automate as much of his work as possible using Microsoft PowerShell. Robert is the author of the books “Learning PowerCLI” and “Learning PowerCLI – Second Edition.” Robert is a frequent contributor and moderator at the VMware VMTN Communities. He has a bachelor degree in software engineering and holds the following IT certifications and accreditations: VSP 2016, VTSP 2016, VCP4-DCV, VCP5-DCV, VCP6-DCV, VCP6-CMA, VCA-Cloud, VCA-WM, VCA-NV, VMSP, VMTSP, ZCS, ZCP, ZCP-Cloud, MCSE, MCSA, MCP, MCP+I, PRINCE2 Foundation and ITIL Foundation. In 2012, 2013, 2014, 2015, 2016, 2017, 2018 and 2019 Robert received the VMware vExpert award for his contribution to the community of VMware users over the past year. In 2017 Robert also received the VMware vExpert Cloud award. PernixData made him in 2015 a member of the PernixPro.

4 Responses to Get VMware vCenter Scheduled Tasks with PowerCLI

  1. Pingback: VMTN Blog: Top 5 Planet V12N Posts – Jan 21st 2013 | Virtualization

  2. Sean says:

    Great Post!
    We have a policy that power on all the virtual machines in the moning every day. However there eight hundreds of virtual machines and we need to create shedule task for each machine one by one. Could you please tell me how to do it by script automatically? Thanks.

    -Sean

    • Hi Sean,

      I am glad that you like my post. Unfortunately I was not able to continue my blog post series on vCenter Scheduled Tasks because I am now writing the “Learning PowerCLI” book. When the book is finished I will try to continue this series.

      To answer your question I used the VMware fling Onyx (http://labs.vmware.com/flings/onyx) to generate the vSphere API code to create a power on VM scheduled task. I made some modifications to the Onyx output to fulfill your needs to create a scheduled task for every virtual machine in your environment.

      The time specified for starting the virtual machines is in UTC or GMT. I live in the Netherlands and our daylight saving time is GMT+2. I specified 5:00 AM, so the virtual machines will be started at 7:00 AM. If you live in a different time zone or you want to power on your virtual machines at another time, then you have to do some time calculations.

      The tasks will send an email to user@domain.com when the task is complete.

      Here is the PowerCLI code to create a recurring vCenter Scheduled Task to power on every virtual machine in your environment at 7:00 AM every morning.

      # ——- CreateScheduledTask ——-
      foreach ($VM in (Get-VM))
      {
      $spec = New-Object VMware.Vim.ScheduledTaskSpec
      $spec.name = “Power on VM $($VM.Name)”
      $spec.description = “Task to Power on VM $($VM.Name)”
      $spec.enabled = $true
      $spec.scheduler = New-Object VMware.Vim.DailyTaskScheduler
      $spec.scheduler.interval = 1
      $spec.scheduler.minute = 0
      $spec.scheduler.hour = 5
      $spec.action = New-Object VMware.Vim.MethodAction
      $spec.action.name = “PowerOnVM_Task”
      $spec.action.argument = New-Object VMware.Vim.MethodActionArgument[] (1)
      $spec.action.argument[0] = New-Object VMware.Vim.MethodActionArgument
      $spec.notification = “user@domain.com”

      $ScheduledTaskManager = Get-View -Id ‘ScheduledTaskManager-ScheduledTaskManager’
      $ScheduledTaskManager.CreateScheduledTask($VM.ExtensionData.MoRef, $spec)
      }

  3. Pingback: How to Create a Scheduled Task in vCenter Server

Leave a comment