Ash
Ash

Reputation: 410

Returning exit code from a batch file in a PowerShell script block

I am trying to call a batch file remotely in a one liner PowerShell command as such:

PowerShell -ExecutionPolicy UnRestricted invoke-command -ComputerName Server1 -ScriptBlock {cmd.exe /c "\\server1\d$\testPath\test.bat"}

What I want to do is return any exit codes from the test.bat file back to my command. Can anyone give me an idea on how to do this?

(PS, for multiple reasons, I am not able to use PSExec).

Cheers

Upvotes: 3

Views: 9951

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175065

You should be able to get the exit code from cmd.exe with the automatic variable $LASTEXITCODE.

If you're interested in only that, and not any output from the batch file, you could change the scriptblock to:

{cmd.exe /c "\\server1\d$\testPath\test.bat" *> $null; return $LASTEXITCODE}

If you're already running powershell, there's no need to invoke powershell again, just establish a session on the remote computer and attach Invoke-Command to it:

$session = New-PSSession remoteComputer.domain.tld
$ExitCode = Invoke-Command -Session $session -ScriptBlock { cmd /c "\\server1\d$\testPath\test.bat" *> $null; return $LASTEXITCODE }
$ExitCode # this variable now holds the exit code from test.bat

Upvotes: 3

Related Questions