3 Replies Latest reply on Sep 21, 2015 1:54 PM by KWKirchner

    PowerCLI issue with snapshot removal - Operation is not valid due to the current state of the object

    KWKirchner Novice

      I have a script I run to delete snapshots that are older than 15 days.  This works fine, except that the actual call to the remove-snapshot cmdlet returns this error:


      Remove-Snapshot : 9/18/2015 4:17:51 AM    Remove-Snapshot        Operation is not valid due to the current state of the object.

      At T:\VMware\PowerCLIScripts\Clean_Snapshots_Sync.ps1:17 char:11

      + $vm | Remove-Snapshot -Confirm:$false

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

      + CategoryInfo          : NotSpecified: (:) [Remove-Snapshot], VimException

      + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.RemoveSnapshot


      But it still works... it just puts it in the vCenter queue.  That's fine except that this has the effect of making this removal run asynchronously even without the -RunAsync flag being set. So I cant just itterate through a list of snapshots. I have to write a loop that monitors the number of snapshot removal tasks that are currently running and sleep until there only 4 (my arbitrary number) running.


      So it works, but I dont know why I am getting that error about the object state.  The queued snapshot removal job begins almost immediately, so what state could it be in for a second that makes the removal report a failure? If it fails, why does it still queue the job? The list of snapshots are pulled into an array prior to looping through the array for the removal, so it shouldnt be interfering with the removal task.


      $VM_Snapshot_List = Get-VM | Get-Snapshot | where { $_.Created -lt (Get-Date).AddDays(($days_old*-1))}
      foreach ($snapshot in $VM_Snapshot_List){
          $snapshot | Select VM,Name,Created
          $running_tasks = get-task -Status Running | where { $_.Name -eq "RemoveSnapshot_Task"}
          while ( $running_tasks.count -ge $max_tasks ){
               write-host "Too many remove tasks! Sleeping for 30 seconds..."
               sleep 30
               $running_tasks = get-task -Status Running | where { $_.Name -eq "RemoveSnapshot_Task"}
          $snapshot | Remove-Snapshot -Confirm:$false