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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With