Score:0

PowerCLI, Invoke-VMScript cannot get the script's exit code

in flag

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?

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.