I have a PowerShell scripts that uses PowerCLI's "Invoke-VMScript" command to start scripts on a sequence of systems. If the script on the first server fails, the controller script should stop. However, Invoke-VMScript doesn't detect the script's exit code. So it can't tell what the error code is.
Here's the 'controller script':
Invoke-VMScript -VM "server1" -GuestCredential $serverCred -ScriptText "powershell c:\server1.ps1" -ScriptType bat
#If server1.ps1 gives an error, this script should stop and not run the following lines.
Invoke-VMScript -VM "server2" -GuestCredential $serverCred -ScriptText "powershell c:\server2.ps1" -ScriptType bat
Invoke-VMScript -VM "server3" -GuestCredential $serverCred -ScriptText "powershell c:\server3.ps1" -ScriptType bat
Here's the script server1.ps1
Get-ChildItem "file_that_doesnt_exist"
exit(10)
If I run the controller script, the output from server1.ps1 is printed to the console, but the exit code is not displayed or reported. Thus, the controller script continues to call server2.ps1 and server3.ps1.
I found a workaround by modifying server1.ps1
try{ Get-ChildItem "file_that_doesnt_exist"}
catch{ "Exit Code 10"}
And modifying the controller
if $($(Invoke-VMScript -VM "server1" -GuestCredential $serverCred -ScriptText "powershell c:\server1.ps1" -ScriptType bat).scriptoutput) -match "Exit Code 10"{
exit(10)}
This will be very hard to maintain. Putting everything in try/catch blocks, then keeping exit codes in all the scripts synced, will be a nightmare.
Is there a better way to get an exit code from a script called on a VM?