View Only
  • 1.  PowerCLI Error Handling

    Posted May 27, 2017 03:25 AM

    I"d like to storage vmotion vms with move-vm and then if there are any errors, put them in an email and email them to me

    get-vm | %{

    move-vm -datastore datastore100


    If one VM fails I don't want to abort the whole script, just catch whatever the error was on that one vm and email it to myself and go to the next one.  Is this possible?

  • 2.  RE: PowerCLI Error Handling
    Best Answer

    Posted May 27, 2017 06:32 AM

    Try something like this

    $Failed = @()

    foreach($vm in Get-VM){


            Move-VM -VM $vm -Datastore datastore100 -ErrorAction SilentlyContinue



            $failed += $vm.Name




        $sMail = @{

            To = ''

            From = ''

            Subject = 'Failed svMotion'

            SmtpServer = ''

            BodyAsHtml = $true

            Body = ($Failed | ConvertTo-Html | Out-String)


        Send-MailMessage @sMail


  • 3.  RE: PowerCLI Error Handling

    Posted May 31, 2017 04:26 PM

    much appreciated again!

  • 4.  RE: PowerCLI Error Handling

    Posted Jun 01, 2017 03:00 AM

    Thanks again - two quick follow up questions on this -

    1. Will this give me the actual details of the error message in red that would normally appear on the powershell session or just the names of the vms that hit an error?  How do I access that actual error message detail for a specific vm that errors out?

    2. Will this continue on migrating the next vm in the list if one before it errors out so that the script doesn't stop?

  • 5.  RE: PowerCLI Error Handling

    Posted Jun 01, 2017 04:52 AM

    1. The last error can be reached via $error[0]

    2. If you don't break out of your script in the Catch code block, the script should continue.

    Unless the Stop was a terminating exception.

    If you don't use the Try-Catch construct, you can add the -ErrorAction SilentlyContinue parameter, then the script will continue.

    But it will be up to your script to check if there was an error (via $error[0] for example)

  • 6.  RE: PowerCLI Error Handling

    Posted Jun 01, 2017 02:50 PM

    OK thanks.  you said $error[0] - in your example code it would be $failed[0] though right?

  • 7.  RE: PowerCLI Error Handling

    Posted Jun 01, 2017 03:43 PM

    No, the $error variable is a system defined variable, it is always there.

    The latest entry is available under $error[0].

    The $failed array in my example is just an array that I used to collect the names of the failed VMs.

  • 8.  RE: PowerCLI Error Handling

    Posted Jun 03, 2017 03:44 AM

    $error[0] works great! thanks again