PowerCLI

 View Only
Expand all | Collapse all

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

  • 1.  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

    Posted Aug 17, 2020 03:26 PM

    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.



  • 2.  RE: 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
    Best Answer

    Posted Aug 17, 2020 03:58 PM

    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



  • 3.  RE: 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

    Posted Aug 17, 2020 04:27 PM

    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.



  • 4.  RE: 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

    Posted Aug 17, 2020 04:37 PM

    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



  • 5.  RE: 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

    Posted Aug 17, 2020 07:05 PM

    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

    }



  • 6.  RE: 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

    Posted Aug 17, 2020 07:32 PM

    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)

    }



  • 7.  RE: 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

    Posted Aug 17, 2020 08:30 PM

    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?

    and this gives the following



  • 8.  RE: 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

    Posted Aug 17, 2020 08:33 PM

    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



  • 9.  RE: 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

    Posted Aug 17, 2020 10:03 PM

    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)

    }



  • 10.  RE: 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

    Posted Aug 18, 2020 11:37 AM

    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)

    }



  • 11.  RE: 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

    Posted Mar 05, 2024 05:30 PM

    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                                      
                }        


  • 12.  RE: 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

    Posted Mar 05, 2024 06:42 PM

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



  • 13.  RE: 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

    Posted Mar 06, 2024 04:39 PM

    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

     



  • 14.  RE: 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

    Posted Mar 06, 2024 05:11 PM

    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'


  • 15.  RE: 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

    Posted Mar 07, 2024 09:56 AM

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



  • 16.  RE: 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

    Posted Nov 19, 2020 01:13 PM

    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



  • 17.  RE: 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

    Posted Sep 25, 2021 02:04 PM

    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.



  • 18.  RE: 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