Hector Minaya
Hector Minaya

Reputation: 1705

VBScript, Batch or PowerShell Script?

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?

Upvotes: 1

Views: 1837

Answers (2)

JimG
JimG

Reputation: 1782

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.

Upvotes: 1

Keith Hill
Keith Hill

Reputation: 201662

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

Upvotes: 1

Related Questions