Search code examples
powershellpsexec

psexec parameter is incorrect


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 
}

Solution

  • 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.