Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 215
Ash Avatar asked Dec 27 '25 23:12

Ash


1 Answers

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
like image 106
Mathias R. Jessen Avatar answered Dec 30 '25 11:12

Mathias R. Jessen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!