VMware Cloud Community
Halukkocaman
Enthusiast
Enthusiast

Schedule Snapshot with PowerCli

Hi All,

I there any way to use PowerCli to schedule a snapshot? I'm looking to built a script to take user inputs such as Vm name, snapshot name, snapshot date, etc. to schedule a snapshot. I'm hoping to create a simple webpage to take some user inputs and pass it to script. I saw some examples that use PowerShell to create schedule task but they are all about creating a windows scheduled task. I would like to create the task as you would create in vSphere.

Thanks,

Haluk

Tags (2)
57 Replies
LauraLeigh
Contributor
Contributor

no, same error when I take out the variable and enter a single VM name

0 Kudos
LucD
Leadership
Leadership

Are you connected to multiple vSphere Servers?
What is in $global:defaultviservers?


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

0 Kudos
LauraLeigh
Contributor
Contributor

I killed all of my powershell sessions, Ran the following command:

Disconnect-Viserver -Server * -Force -Confirm:$false

Then ran the script, and I am now getting this error on the last line:

Exception calling "CreateObjectScheduledTask" with "2" argument(s): "A specified

parameter was not correct: "

0 Kudos
LucD
Leadership
Leadership

Did you already try with 1 email address instead of an array?


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

0 Kudos
LauraLeigh
Contributor
Contributor

Yes, same error was received:

Exception calling "CreateObjectScheduledTask" with "2" argument(s): "A specified

parameter was not correct: "

0 Kudos
LucD
Leadership
Leadership

I have to come back to my original question, are you sure that only 1 VM is returned when you do a Get-VM with that name?
That's for now the only possibility I see.

The error states that it receives an array where it expects a single value.

You could also check by doing a

$spec | Format-Custom -Depth 2

before calling the method.


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

0 Kudos
LauraLeigh
Contributor
Contributor

Yes I'm sure. The output when adding that line:

class ScheduledTaskSpec

{

  Name = Snapshot

  Description = Take a snapshot of servername

  Enabled = True

  Scheduler =

    class OnceTaskScheduler

    {

      RunAt =

        class DateTime

        {

          Date = 5/4/2019 12:00:00 AM

          Day = 4

          DayOfWeek = Saturday

          DayOfYear = 124

          Hour = 17

          Kind = Unspecified

          Millisecond = 0

          Minute = 30

          Month = 5

          Second = 0

          Ticks = 636925878000000000

          TimeOfDay = 17:30:00

          Year = 2019

          DateTime = Saturday, May 4, 2019 5:30:00 PM

        }

      ActiveTime =

      ExpireTime =

    }

  Action =

    class MethodAction

    {

      Name = CreateSnapshot_Task

      Argument =

        [

          VMware.Vim.MethodActionArgument

          VMware.Vim.MethodActionArgument

        ]

       

    }

  Notification = <someone@somewhere.com>

}

0 Kudos
LucD
Leadership
Leadership

That looks ok.


I just tried your exact code in my test environment, and it creates the scheduled task without an issue.

I'm using PowerCLI 11.2 against a vSphere 6.7 environment.

The error message states that it receives an array where it expects a MoRef.
The only place where that happens is with the 1st parameter to the CreateObjectScheduledTask method, which is the $vm.ExtensionData.MoRef value.

But since you confirmed that $vm only holds a single VM, I have no other explanation where the problem can come from.


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

0 Kudos
prashantpote
Contributor
Contributor

1) Snapshot not created by below script, Let me know if any changes required(Already logged in to vCenter through powercli and my details replaced with xxxxx in below script) :
 
##############################################################################################
 
$snapTime = Get-Date "05/04/19 12:31"
$snapName = 'Test'
$snapDescription = 'Test Scheduled snapshot'
$snapMemory = $true
$snapQuiesce = $false
$emailAddr = 'xxx@xxx.com'
$fileName = 'C:\Users\snapshots.csv'
$vcName = 'vcenter6.xxxx.com'
######################################################################
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",$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"
    
    @($snapName,$snapDescription,$snapMemory,$snapQuiesce) | %{
        $arg = New-Object VMware.Vim.MethodActionArgument
        $arg.Value = $_
        $spec.Action.Argument += $arg
    }
    
    $scheduledTaskManager.CreateObjectScheduledTask($vm.ExtensionData.MoRef, $spec)
}
 
===============================================================
Output was :
Type          Value
----          -----
ScheduledTask schedule-201
ScheduledTask schedule-20
 
================================================
 
2) Snapshot not created by script and task generated in vCenter "Created schduled task".
 
3) Giving error when I reran the script for testing :
 
Exception calling "CreateObjectScheduledTask" with "2" argument(s): "The name 'Snapshot TEST1234' already exists."
At C:\Users\ScheduleSnap.ps1:67 char:5
+     $scheduledTaskManager.CreateObjectScheduledTask($vm.ExtensionData ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException
 
4) Most important, how to remove or delete created scheduled task from vCenter. ???
0 Kudos
LucD
Leadership
Leadership

1) Script looks ok.

When you see MoRefs being returned it means the ScheduledTasks are created

2) Note that the time you pass to the CreateObjectScheduledTask method is in UTC.
You will have to make sure that you specify a time, when converted to your local time, is in the future.

When the scheduled time is past, the task will not run.

3) You are trying to create a ScheduledTask that already exists with that Name

4) To remove a ScheduledTask, you can do

$taskName = 'Test123'

$si = Get-View ServiceInstance

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

Get-View -Id $scheduledTaskManager.ScheduledTask |

ForEach-Object -Process {

   if ($_.Info.Name -eq $taskName)

   {

   $_.RemoveScheduledTask()

   }

}


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

0 Kudos
prashantpote
Contributor
Contributor

Removed task successfully. but still confused with Date time as I have tried with using vcenter UTC date time. Script not running(without error without output)
0 Kudos
LucD
Leadership
Leadership

Is there in the Web Client nothing in the Last Run columns?


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

0 Kudos
prashantpote
Contributor
Contributor

No events in vCenter when ran script 😞
0 Kudos
LucD
Leadership
Leadership

I find that hard to understand, you showed that you got 2 MoRefs returned.
So at least 2 Scheduled Tasks should be there.


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

0 Kudos
dowlesm
Contributor
Contributor

Since this thread is pretty old you've probably found your answer but I beat my head against this for hours and finally found a reference on the VMWare site that mentioned in order to create a scheduled task you would call the ScheduledTaskManager.CreateScheduledTask method. Online Documentation - VMware vSphere Web Services SDK Programming Guide - VMware {code}

Remove the word Object and change the last line to  $scheduledTaskManager.CreateScheduledTask($vm.ExtensionData.MoRef,$spec)

0 Kudos
daye
Contributor
Contributor

Does this work for connecting to multiple Vcenters, the VMs I am going to take snapshots are cross serveral Vcenters.

 

Thank you,

0 Kudos
LucD
Leadership
Leadership

You will have to know on which vCenter a VM is located.
Then use the Server parameter on the Get-View cmdlet, pointing to that specific vCenter.

You can find the vCenter for a VM with

([Uri]$vm.ExtensionData.Client.ServiceUrl).Host


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

0 Kudos
satish_rsi
Contributor
Contributor

Hi LucD,

 

The script worked fine until I upgraded my VCSA to 8.0 U2a from 7.x. I'm getting below error while executing the command:

Exception calling "CreateObjectScheduledTask" with "2" argument(s): "A general system error occurred: Error while getting Persistable Token for Session User from TES"
At line:65 char:5
+ $scheduledTaskManager.CreateObjectScheduledTask($vm.ExtensionData ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException

Please help on this as we get lot of snapshot tickets daily.

0 Kudos
LucD
Leadership
Leadership

Never seen that error before I have to admit.
Not sure what this "... from TES" means.

I would suggest opening an SR


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

0 Kudos
satish_rsi
Contributor
Contributor

Sure LucD...I will let you know what they suggest on this.

0 Kudos