VMware Cloud Community
CompassITCanada
Contributor
Contributor
Jump to solution

vSphere 6.7 VCSA Cannot Edit Scheduled tasks through GUI, need to create a script to delete all Scheduled Tasks and then re-create them with correct runtimes

I have manually created scheduled tasks for all my prod VMs to take snapshots and send confirmation email at specific times which are prior to allowing Windows Updates.

Some of these jobs ran ok and others did not even start. Furthermore I cannot edit them, I would need to delete and recreate them.

I am hoping for some help to create a script to delete all Scheduled Tasks with a specific job name like following but I need to know how to do the delete.

Get-VIScheduledTasks | Where-Object {$_.Name -like '*PRE WSUS*'} | Format-Table -Autosize

Once I have done this I want to create a script which pulls in VM names and other fields like time and snapshot names from a CSV to create the scheduled tasks.

I see some scripts for this which I can borrow from but any help much appreciated.

1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

To remove the scheduled tasks you could do

$si = Get-View ServiceInstance

$sTaskMgr = Get-View -Id $si.Content.ScheduledTaskManager

Get-View -Id $sTaskMgr.ScheduledTask |

where{$_.Info.Name -match 'PRE WSUS'} |

ForEach-Object -Process {

    $_.RemoveScheduledTask()

}

To create the new scheduled tasks you should share the layout of your CSV


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

17 Replies
LucD
Leadership
Leadership
Jump to solution

To remove the scheduled tasks you could do

$si = Get-View ServiceInstance

$sTaskMgr = Get-View -Id $si.Content.ScheduledTaskManager

Get-View -Id $sTaskMgr.ScheduledTask |

where{$_.Info.Name -match 'PRE WSUS'} |

ForEach-Object -Process {

    $_.RemoveScheduledTask()

}

To create the new scheduled tasks you should share the layout of your CSV


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

CompassITCanada
Contributor
Contributor
Jump to solution

Thanks LucD you are a star. I will try that now.

As for CSV I havent created it yet, all I need really are:

VMName

TaskName

TaskDescription

Time / date - 2nd day of each month

Email address.

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

To create the new scheduled tasks you might want to have a look at Re: Help with Scheduled Snapshot Task using CSV

I think most of what you want to do is in there


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

CompassITCanada
Contributor
Contributor
Jump to solution

LucD - trying to work it out on my own but need your help again please? I'm not sure why I get this error or if I'm on right track? Thanks in advance for your help

Exception calling "CreateObjectScheduledTask" with "2" argument(s): "A specified parameter was not correct:. The value '0'

for the interval is not in the range 1-1000 for the scheduler."

At Z:\InformationTechnology\PS Scripts\CreateWSUSScheduledTasks.ps1:56 char:1

+ $scheduledTaskManager.CreateObjectScheduledTask($vm.ExtensionData.MoR ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : VimException

# CSV File Format

# VMName,Description,Quiesce

# VM1,Test1,n

##########################

# Do we quiesce or not

$QS = $_.Quiesce

if($QS -eq 'y') {

$snapMemory = $true

$snapQuiesce = $true

}else{

$snapMemory = $false

$snapQuiesce = $false

}

# $snaptime = Get-Date "08/17/20 14:30"

$emailAddr = 'cvl-vmwarealerts@helixit.ca'

$fileName = 'Z:\InformationTechnology\PS Scripts\snapshots.csv'

##############

Import-Csv -Path $fileName -UseCulture | %{

# Verify the scheduled task name is not already in use

$vm = Get-VM -Name $_.VMName

$si = get-view ServiceInstance

$scheduledTaskManager = Get-View $si.Content.ScheduledTaskManager

$spec = New-Object VMware.Vim.ScheduledTaskSpec

$spec.Scheduler = New-Object VMware.Vim.MonthlyByWeekdayTaskScheduler

$spec.Scheduler.Offset = [VMware.Vim.WeekOfMonth]::second

$spec.Scheduler.Weekday = [VMware.Vim.DayOfWeek]::tuesday

$spec.Scheduler.Hour = 14

$spec.Scheduler.Minute = 45

$spec.Name = "PRE WSUS SNAPSHOT OF",$vm.Name -join ' '

$spec.Description = $_.Description

$spec.Enabled = $true

$spec.Notification = $emailAddr

#$spec.Scheduler = New-Object VMware.Vim.OnceTaskScheduler

#$spec.Scheduler.runat = $_.snaptime

$spec.Action = New-Object VMware.Vim.MethodAction

$spec.Action.Name = "CreateSnapshot_Task"

@($spec.Name,$spec.Description,$QS) | %{

$arg = New-Object VMware.Vim.MethodActionArgument

$arg.Value = $_

$spec.Action.Argument += $arg

}

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Starting from a CSV with the this layout.

VMName,Description,StartTimeHour,StartTimeMin,Repeat,StartDate

TestVM,'Test task',14,15,10,9/1/2020 00:00:00

you could run like this.
This will run the task on the 2nd Tuesday of each month at 14:15, for 10 months and starting on Sep 1st 2020.

##########################

$snapMemory = $false

$snapQuiesce = $true

$emailAddr = 'xxx@xxx.com'

$fileName = 'C:\Temp\Scripts\VMware PowerCLI\snapshot-weekly.csv'

Import-Csv -Path $fileName -UseCulture | %{

    $vm = Get-VM -Name $_.VMName

    $si = get-view ServiceInstance

    $scheduledTaskManager = Get-View $si.Content.ScheduledTaskManager

    $spec = New-Object VMware.Vim.ScheduledTaskSpec

    $spec.Name = "Snapshot of",$vm.Name -join ' '

    $spec.Description = $_.Description

    $spec.Enabled = $true

    $spec.Notification = $emailAddr

    $obj = New-Object -TypeName VMware.Vim.MonthlyByWeekdayTaskScheduler

    $obj.Offset = [VMware.Vim.WeekOfMonth]::second

    $obj.Weekday = [VMware.Vim.DayOfWeek]::tuesday

    $obj.Hour = $_.StartTimeHour

    $obj.Minute = $_.StartTimeMin

    $obj.Interval = $_.Repeat

    $obj.ActiveTime = [DateTime]($_.StartDate)

    $spec.Scheduler = $obj

    $spec.Action = New-Object VMware.Vim.MethodAction

    $spec.Action.Name = "CreateSnapshot_Task"

    @($spec.Name,$spec.Description,$snapMemory,$snapQuiesce) | %{

        $arg = New-Object VMware.Vim.MethodActionArgument

        $arg.Value = $_

        $spec.Action.Argument += $arg

    }

    $scheduledTaskManager.CreateScheduledTask($vm.ExtensionData.MoRef, $spec)

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

CompassITCanada
Contributor
Contributor
Jump to solution

Luca thanks so much. That works to a point but it needs some fine tuning and I cannot get the times right. Tried different combinations trying to factor in UTC and the local timezone which is PST but it seems to have a start time of 7pm if I enter 00 for hour, so I used 05 and it was 9pm then I used 12 and it was 8pm - weird.

Should I consider using the Get-Time function?

Screen Shot 2020-08-17 at 4.25.27 PM.png and this gives the following

Screen Shot 2020-08-17 at 4.17.07 PM.png

Reply
0 Kudos
CompassITCanada
Contributor
Contributor
Jump to solution

Forgot to add ultimately I want to schedule for 00:01 maybe with a 2 minute interval between snaps if that is possible

thanks

Twister

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

The start time is expected to be in UTC, so you'll have to convert it.

If you want the snapshots to start at 00:01 and then every 2 minute interval, you could do

The CSV can be updated to

VMName,Description,Repeat,StartDate

ubuntubionicps,'Test task',10,9/1/2020 00:00:00

ubuntufocalps,'Test task',10,9/1/2020 00:00:00

##########################

$snapMemory = $false

$snapQuiesce = $true

$emailAddr = 'xxx@xxx.com'

$fileName = 'C:\Temp\Scripts\VMware PowerCLI\snapshot-weekly.csv'

###############

$startTime = (Get-Date -Hour 0 -Minute 1).ToUniversalTime()


Import-Csv -Path $fileName -UseCulture | %{

    $vm = Get-VM -Name $_.VMName

    $si = get-view ServiceInstance

    $scheduledTaskManager = Get-View $si.Content.ScheduledTaskManager

    $spec = New-Object VMware.Vim.ScheduledTaskSpec

    $spec.Name = "Snapshot of",$vm.Name -join ' '

    $spec.Description = $_.Description

    $spec.Enabled = $true

    $spec.Notification = $emailAddr

    $obj = New-Object -TypeName VMware.Vim.MonthlyByWeekdayTaskScheduler

    $obj.Offset = [VMware.Vim.WeekOfMonth]::second

    $obj.Weekday = [VMware.Vim.DayOfWeek]::tuesday

    $obj.Hour = $startTime.Hour

    $obj.Minute = $StartTime.Minute

    $startTime = $startTime.AddMinutes(2)

    $obj.Interval = $_.Repeat

    $obj.ActiveTime = [DateTime]($_.StartDate)

    $spec.Scheduler = $obj

    $spec.Action = New-Object VMware.Vim.MethodAction

    $spec.Action.Name = "CreateSnapshot_Task"

    @($spec.Name,$spec.Description,$snapMemory,$snapQuiesce) | %{

        $arg = New-Object VMware.Vim.MethodActionArgument

        $arg.Value = $_

        $spec.Action.Argument += $arg

    }

    $scheduledTaskManager.CreateScheduledTask($vm.ExtensionData.MoRef, $spec)

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

CompassITCanada
Contributor
Contributor
Jump to solution

Hi LucD,

Thanks for your help. I ended up messing with times and got there eventually. For interval I just modified the minutes in CSV file

Need to be something like this 12,1,1,dd/mm/yyyy 04:01:00 for PST runtime of 12:01am on dd/mm/yyyy

Do you do any freelancing / contracting? if so ping me on twister@compassnet.ca as I'd love to use you if I can at some point?

This is what I ended up with for code that works for my situation.

thanks again

Twister

##########################

$emailAddr = 'cvl-vmwarealerts@xxx.xxx'

$fileName = 'Z:\InformationTechnology\PS Scripts\WSUSMonthlyJobs.csv'

#$fileName = 'Z:\InformationTechnology\PS Scripts\Test18thAug.csv'

Import-Csv -Path $fileName -UseCulture | %{

$QS = $_.Quiesce

if($QS -eq 'y') {

$snapMemory = $true

$snapQuiesce = $true

}else{

$snapMemory = $false

$snapQuiesce = $false

}

    $vm = Get-VM -Name $_.VMName

    $si = get-view ServiceInstance

    $scheduledTaskManager = Get-View $si.Content.ScheduledTaskManager

    $spec = New-Object VMware.Vim.ScheduledTaskSpec

    $spec.Name = "Pre WSUS Update snapshot of",$vm.Name -join ' '

    $spec.Description = $_.Description

    $spec.Enabled = $true

    $spec.Notification = $emailAddr

    $obj = New-Object -TypeName VMware.Vim.MonthlyByWeekdayTaskScheduler

    $obj.Offset = [VMware.Vim.WeekOfMonth]::third

    $obj.Weekday = [VMware.Vim.DayOfWeek]::Tuesday

    $obj.Hour = $_.StartTimeHour

   # $obj.Minute = $_.StartTimeMin - didn't seem to make any difference what this was set to

    $obj.Interval = $_.Repeat

    $obj.ActiveTime = [DateTime]($_.StartDate)

    $spec.Scheduler = $obj

    $spec.Action = New-Object VMware.Vim.MethodAction

    $spec.Action.Name = "CreateSnapshot_Task"

    @($spec.Name,$spec.Description,$snapMemory,$snapQuiesce) | %{

        $arg = New-Object VMware.Vim.MethodActionArgument

        $arg.Value = $_

        $spec.Action.Argument += $arg

    }

    $scheduledTaskManager.CreateScheduledTask($vm.ExtensionData.MoRef, $spec)

}

Reply
0 Kudos
sgreymont
Contributor
Contributor
Jump to solution

Thank you for this code snipit - saved me from a long task of manually cleaning up hundreds of old tasks

I changed the line from -match to -like and I was able to remove hundreds of one time scheduled snapshots or after hour migrations

Reply
0 Kudos
system_noida
Enthusiast
Enthusiast
Jump to solution

HI Luc,

 

I want to input the VM name from a CSV file to delete the scheduled task from multiple VMs , please can you help which code I need to put and where.

Reply
0 Kudos
imlopes
Contributor
Contributor
Jump to solution

The scripts work fine, but at the same time the Snapshot is scheduled, IDK why I receive the error that the snapshot schedule already exists:

 

Line |144 | …$scheduledTaskManager.CreateScheduledTask($vm.ExtensionData.MoRef, $spec)| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Exception calling "CreateScheduledTask" with "2" argument(s): "The name '2024-03-05-0555-serverName.org' already exists."

 

 if($line -match [System.String]::Concat($server.Name, ".") -and $line -NotMatch 'replica$'){      
             
                Write-Host $line.ToUpper()                
               
                $snapName = ($snapTime.ToString("yyyy-MM-dd-hhmm")) + '_SCCM_Snapshot'
               
                $vm = Get-VM -Name $line
                $snapDescription = ($snapTime.ToString("yyyy-MM-dd-hhmm")) + ' SCCM SQL Test'            
                $snapMemory = $false            
                $snapQuiesce = $false                        
                ###############                      
                $si = get-view ServiceInstance            
                $scheduledTaskManager = Get-View $si.Content.ScheduledTaskManager            
                $spec = New-Object VMware.Vim.ScheduledTaskSpec            
                $spec.Name = ($snapTime.ToString("yyyy-MM-dd-hhmm")) + "-$line",$_.VMname -join ' '            
                $spec.Description = "Take a snapshot of $line"            
                $spec.Enabled = $true                    
                $spec.Scheduler = New-Object VMware.Vim.OnceTaskScheduler            
                $spec.Scheduler.runat = $snapTime            
                $spec.Action = New-Object VMware.Vim.MethodAction            
                $spec.Action.Name = "CreateSnapshot_Task"  
               
                @($snapName,$snapDescription,$snapMemory,$snapQuiesce) | %{            
                    $arg = New-Object VMware.Vim.MethodActionArgument            
                    $arg.Value = $_            
                    $spec.Action.Argument += $arg            
                }        
   
                $scheduledTaskManager.CreateScheduledTask($vm.ExtensionData.MoRef, $spec) |
               
               
                #$message = "$timestamp Scheduling "+$snapName+" snapshot for VM "+$line
                #Write-Host $message
                Add-Content -Path $log_path -Value "$timestamp`t$snapName`t$line`t($snapTime.ToString('yyyy-MM-dd-hhmm'))"
                #Add-Content -Path $log_path -Value $message                                      
            }        
Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Do you perhaps have multiple connections to the VCSA open?
Check what is in $global:defaultVIServers


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
imlopes
Contributor
Contributor
Jump to solution

As I have 2 vCenters in 2 diferent locations I connect in both:

PS P01:\> $global:defaultVIServers

Name Port User
---- ---- ----
bra-vcenter.domain.org 443 domain\user
bel-vcenter.domain.org 443 domain\user

 

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Then you have to use the Server parameter to indicate for which vCenter you want to create the scheduled task.
From the error it looks as if the scheduled task already exists on one of the vCenters.

$si = get-view ServiceInstance -Server 'targetted-vcenter'
$scheduledTaskManager = Get-View $si.Content.ScheduledTaskManager -Server 'targetted-vcenter'


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
imlopes
Contributor
Contributor
Jump to solution

Tks LucD, I'll try it and post here the results =D

Reply
0 Kudos