Reply to Message

View discussion in a popup

Replying to:
stanj
Enthusiast
Enthusiast

How do I exit PowerCLI on an error in a script running in Windows Scheduler

I have the below script that runs that will clone a VM (found this is s Luc D script).  It was working, but then the account password changed so the task failed.  But, task scheduler still shows it completed and the script running which wil lkick off at 9PM - (below is what is in the task Scheduler under the Task Actions)

c:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe e:\CLIscripts\CloneVMidm02.ps1

If for some reason the VM is removed or there is an issue, the task scheduler still shows the script runs, but i see no error.

What do i need to add to the below so that if an error occurs,  the error is shown in a log or in the task scheduler History? 

Assume the connection is made to vCenter with an encrypted password

$vcenter_server = "vcenter7"

$user = 'maint1@vsphere.local'
$Folder = “IDM02 Clones”
$vmName = 'idm02'

 

Connect-VIServer -Server $vcenter_server -User $user -Password $decryptedPassword

Set-PowerCLIConfiguration -DisplayDeprecationWarning:$true

$ds = Get-Datastore | where{$_.Type -eq 'VMFS' -and $_.ExtensionData.Summary.MultipleHostAccess} |
Sort-Object -Property FreeSpaceGB -Descending | select -First 1

$esx = Get-Cluster -VM $vmName | Get-VMHost | Get-Random

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Set up cloning names -
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

$cloneName = "$($vmName)-clone-$((Get-Date).ToString('MMddyyyy'))"
$oldCloneName = "$($vmName)-clone-$((Get-Date).AddDays(-1).ToString('MMddyyyy'))"

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Get the idm02 clone and remove the day before clone
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Get-VM -Name $oldCloneName -ErrorAction SilentlyContinue |
Remove-VM -DeletePermanently:$true -Confirm:$false


#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Clone idm02 to current day
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#

New-VM -VM $vmName -Name $cloneName -Datastore $ds -Location $Folder -VMHost $esx

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# disconnect from vCenter
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!

Disconnect-VIServer -Server $vcenter_server -Confirm:$false

exit

Reply
0 Kudos