0

I am using psexec to execute a .bat on a system. This will fingerprint the system and return the info back to me. The command I use is:

psexec \\server -u username -p password -s -i -c .\fingerprint.bat 

This works with most of the servers, but some of them won't work with the -i switch. Is there a way to say, if this fails, try to do it again without the -i? I am using powershell to execute the script.

$servers = get-content .\input.txt

foreach($server in $servers) {
   psexec \\$server -u username -p password -s -i -c .\fingerprint.bat 
}
Jeff
  • 4,285
  • 15
  • 63
  • 115
  • never worked with powershell, but there must be some way of capturing the exec code of psexec. e.g. some equivalent of bash's `$!`. – Marc B Feb 14 '13 at 16:13

1 Answers1

2

Check the $LastExitCode automatic variable. This gets set when PowerShell invokes an EXE. Whatever exit code the EXE returns gets put in $LastExitCode. I'm pretty sure psexec returns 0 for success and anything else means failure e.g.:

foreach($server in $servers) {
   psexec \\$server -u username -p password -s -i -c .\fingerprint.bat 
   if ($LastExitCode) {
       psexec \\$server -u username -p password -s -c .\fingerprint.bat 
   }
}

This is using a PowerShell trick where if ($LastExitCode) will if evaluate to true if $LastExitCode is anything but 0.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • I will be using if($lastExitCode -ne 0) . Thanks very much. Any way to get the the last error message? – Jeff Feb 15 '13 at 15:44
  • You should be able to catch stderr/stdout output like so: `$res = psexec ... .\fingerprint.bat 2>&1`. – Keith Hill Feb 15 '13 at 16:45