I have to call a PowerShell script from outside PowerShell (using a batch file).How do I read the exit code returned by the script after accessing a remote system?
C:\gdp>powershell Get-Content ./test15.ps1param($name)Get-Process -Name $name
exit 82
-----
Example 1 (local):
C:\gdp>powershell -noprofile ./test15.ps1 explorer ; exit $LASTEXITCODE
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName------- ------ ----- ----- ----- ------ -- ----------- 379 18 9768 5780 108 5,02 4016 explorer
C:\gdp>echo %ERRORLEVEL%82
Example 2 (remote access):
C:\gdp>powershell -noprofile Invoke-Command -Computername remote-server -Filepath ./test15.ps1 -Argumentlist explorer ; exit $LASTEXITCODE
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName PSComputerName------- ------ ----- ----- ----- ------ -- ---------- ---------- 626 38 25304 47868 241 31,73 3728 explorer remote-server
C:\gdp>echo %ERRORLEVEL%0 <------------ (expected result: 82)
Of course, I get the desired result if the script runs inside PowerShell.Example 3 (inside PowerShell):
PS C:\gdp> Invoke-Command -Computername remote-server -Filepath ./test15.ps1 -Argumentlist explorer
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName PSComputerName------- ------ ----- ----- ----- ------ -- ----------- -------------- 626 38 25304 47868 241 31,91 3728 explorer remote-server
PS C:\gdp> $LASTEXITCODE82
Ideas?
You could consider running the Invoke-Command -AsJob and then using the JobStateInfo to get either a State value or Reason string:
$job = Invoke-Command -ComputerName test -ScriptBlock {dir} -asjob ; $job.JobStateInfo
If Invoke-Command is run against multiple computers it gets a little more complicated since you end up with a collection of jobs:
job-> child job for each computer
You basically need to traverse the collection of job children to get at each JobStateInfo.
Thanks for the info. I'll look into it.
As a side note, I just noticed that the LASTEXITCODE in example 3 is the one generated by example 1.