PowerCLI

 View Only
  • 1.  How do I exit PowerCLI on an error in a script running in Windows Scheduler

    Posted Sep 07, 2023 03:11 PM

    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



  • 2.  RE: How do I exit PowerCLI on an error in a script running in Windows Scheduler

    Posted Sep 07, 2023 03:23 PM

    Do you mean the password for the account under which the task runs in the Windows Task Scheduler?
    Or the password for the account with which you run the Connect-VIServer?

    To capture errors inside the script you can use Try-Catch construct.
    If a cmdlet should fail with a non-terminating exception, you can always add an -ErrorAction Stop to force a terminating exception.

    When an exception occurs, you code will end up in the Catch block, where you could pass another exit code.
    Which should also be reflected in the Task in the Windows Task Scheduler.

    For example, to capture a non-existing VM, you could do

    Try {
       $esx = Get-Cluster -VM $vmName -ErrorAction Stop | Get-VMHost | Get-Random
    
       # The rest of your code
    
       exit 0  # All went well
    }
    Catch {
       exit 1  # Error encountered
    }





  • 3.  RE: How do I exit PowerCLI on an error in a script running in Windows Scheduler

    Posted Sep 07, 2023 03:37 PM

    Thanks Luc

     

    I mean the username password for connecting to vcenter with  Connect-VIServer

    When that happened, the connection failed and the cloning did not take place for that day and the names were off by a few days.

    So, i think the ..Get-VM -Name $oldCloneName -ErrorAction SilentlyContinue | Remove-VM -DeletePermanently:$true -Confirm:$false failed because the oldCloneName is based on a day that there was no cloning 

    Let me add the block and see if it catches the issue.



  • 4.  RE: How do I exit PowerCLI on an error in a script running in Windows Scheduler

    Posted Sep 07, 2023 03:49 PM

    You can also add the ErrorAction parameter on the Connect-VIServer cmdlet.
    In the Catch block you find more information in the $error[0] variable about the exception.



  • 5.  RE: How do I exit PowerCLI on an error in a script running in Windows Scheduler

    Posted Sep 11, 2023 08:45 PM

    I have to drop back to the below code to ask a question before trying the error code,,,,

    Question is at the bottom,.,

    ------------------------------------------------------

    Set-PowerCLIConfiguration -Scope User -ParticipateInCEIP $false -Confirm:$false

    Set-PowerCLIConfiguration -DisplayDeprecationWarning:$true

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

    $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 - remove the day before
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    $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 curernt day
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #

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

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

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

    exit 0

    ------------------------------------------------------------------------ 

    If I go to the Task Manager in Windows and right click on the task and select run to execute the above script,  I get a PowerShell window that pops up with the below and the window just stays up. 

    How do I stop the PowerShell window from opening when I right click and select "run"?


    Scope ProxyPolicy DefaultVIServerMode InvalidCertificateAction DisplayDeprecationWarnings WebOperationTimeout
    Seconds
    ----- ----------- ------------------- ------------------------ -------------------------- -------------------
    Session UseSystemProxy Single Ignore True 300
    User Single Ignore True
    AllUsers

    Perform operation?
    Performing operation 'Update PowerCLI configuration.'?
    [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):

     



  • 6.  RE: How do I exit PowerCLI on an error in a script running in Windows Scheduler

    Posted Sep 11, 2023 09:32 PM

    What kind of file do you right-click on and select Run?
    Is that a .ps1 file?

    When you start a script with powershell.exe, like you would do in Windows Task Scheduler, you add the -NonInteractive parameter.
    But you have to make sure that your script is not causing any interactive prompts.
    Your 2nd Set-PowerCLIConfiguration does not contain the -Confirm:$false parameter, so there will be a prompt.



  • 7.  RE: How do I exit PowerCLI on an error in a script running in Windows Scheduler

    Posted Sep 11, 2023 09:43 PM

    It is a .ps1 file

    Where is the -NonInteractive parameter added ?

    In side the .ps1 script or as a parameter in the task job within scheduler (below screen)?

     

    stanj_0-1694468549199.png

     



  • 8.  RE: How do I exit PowerCLI on an error in a script running in Windows Scheduler

    Posted Sep 11, 2023 10:19 PM

    I added -NonInteractve below.  When I right click the task and select run, the Powershell screen flashes up and now I see a 0x1 in the Last Run Results in Task Scheduler

     

    stanj_0-1694470553634.png

     



  • 9.  RE: How do I exit PowerCLI on an error in a script running in Windows Scheduler

    Posted Sep 12, 2023 06:15 AM

    Exit code 1 means that an uncaught Throw happened (i.e. a terminating exception).
    See Windows PowerShell Exit Codes

    With the Try-Catch I mentioned earlier you can use different exit codes in the Catch block to clarify what went wrong.