3

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

1
  • The .bat has a conditional exit in it. Depending on what occurs during the process, the exit may be set to any number of codes (in the 5000 to 5999 range). The last line of the .bat is exit _nnnn_ if any of the failure conditions are met or exit 0 if everything is OK. Commented Nov 16, 2015 at 21:51

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

OK, what I want to do is bubble that $LASTEXITCODE back up to the calling command so I can exit out of the process back to the calling command with that code. With the above, I am still getting a zero process exit code.
Right, I have figured out what I needed to do to get it to bubble all the way to the top as a one liner: powershell -ExecutionPolicy UnRestricted; $var = "& invoke-command -ComputerName Server1 -ScriptBlock {cmd.exe /c '\\Server1\d$\testPath\test.bat' *> $null; return $LASTEXITCODE}"; exit $var . Thanks for your help. It most certainly pointed me in the direction I needed.
what if you need the output as well?
@RobertIvanc Construct an object (using New-Object or equivalent) inside the scriptblock that contains both?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.