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?
Try something like this
$Failed = @()
foreach($vm in Get-VM){
Try{
Move-VM -VM $vm -Datastore datastore100 -ErrorAction SilentlyContinue
}
Catch{
$failed += $vm.Name
}
}
if($Failed){
$sMail = @{
To = 'lucd@lucd.info'
From = 'lucd@lucd.info'
Subject = 'Failed svMotion'
SmtpServer = 'mail.lucd.info'
BodyAsHtml = $true
Body = ($Failed | ConvertTo-Html | Out-String)
}
Send-MailMessage @sMail
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Try something like this
$Failed = @()
foreach($vm in Get-VM){
Try{
Move-VM -VM $vm -Datastore datastore100 -ErrorAction SilentlyContinue
}
Catch{
$failed += $vm.Name
}
}
if($Failed){
$sMail = @{
To = 'lucd@lucd.info'
From = 'lucd@lucd.info'
Subject = 'Failed svMotion'
SmtpServer = 'mail.lucd.info'
BodyAsHtml = $true
Body = ($Failed | ConvertTo-Html | Out-String)
}
Send-MailMessage @sMail
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
much appreciated again!
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?
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)
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
OK thanks. you said $error[0] - in your example code it would be $failed[0] though right?
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.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
$error[0] works great! thanks again