views:

346

answers:

2

I'm trying to run various commands using psexec.exe from Windows Sysinternals. What I need is a simple script to read the output of those commands.

For example if everything went OK, then it returns a 0. If something went wrong, then it will spit out an error code.

How can it be done?

+1  A: 

In PowerShell, you would use the $LastExitCode variable to test if psexec succeeded or not e.g.:

$results = psexec <some command on remote system>
if ($LastExitCode -ne 0) {
    throw "PSExec failed with error code $LastExitCode"
}
return 0
Keith Hill
+1  A: 

In a batch file, you use the %ERRORLEVEL% variable, or the IF ERRORLEVEL n command. For example:

psexec \\host -i findstr.exe "test" c:\testfile
if errorlevel 1 (
  echo A problem occurred
)

IF ERRORLEVEL checks whether the return value is the same or higher than the number you specify.

This is not the same as capturing the output of the command though. If you actually want the output, you need to include redirection to an output file on the command line:

psexec \\host -i cmd.exe /c findstr "test" c:\testfile ^> c:\output.txt

The ^ is necessary to escape the > character, or the redirection would happen locally instead of on the remote machine. The cmd.exe is necessary, because redirection is handled by cmd.

JimG
`%errorlevel%` is only a pseudo-variable, expanded on the fly by the shell. Just as `%time%`, `%random%` and others.
Joey