TripleNad
TripleNad

Reputation: 65

Passing CMD Results to Variable in a Batch File

I am trying to install an application and a group of services using PSTools, but I want to take into account that the computer I am trying to connect to may be turned off or on a different network, which is not reachable from the internal network.

Basically if the machine is not able to be accessed through the admin share, this is the message that I am getting:

Couldn't access MachineName:
The network path was not found.
Make sure that the default admin$ share is enabled on MachineName.

This is the syntax I am using to try to capture the "Error Message" and then report back that if installation was successful or not (depending on if it can contact the machine)

@echo off
set /p name=What is the machine name?: 
psexec.exe \\%name% -u *useraccount* -p *password* \\ServerName\installation.bat
FOR /F "tokens=*" %%A IN ('COMMAND ^| FIND "Couldn't access"') DO SET Error=%%A
If "%Error%"=="Couldn't access" 
ECHO Installation Failed.
Else
ECHO Installtion complete.  
Pause
exit

Currently it hangs right at the point it's defining the Error Variable. Can't quite figure out what I am going wrong here.

Upvotes: 2

Views: 1341

Answers (1)

SeanC
SeanC

Reputation: 15923

'COMMAND ^| FIND "Couldn't access"' opens a command shell, which is why it hangs. It will not proceed until that shell is exited.

You will need to look at redirecting the error messages to another file. 2>Errors.txt on the psexec line will give you a file to search in the next line.

this will make the batch file look something like this:

@echo off
set /p name=What is the machine name?: 
psexec.exe \\\%name% ... \\\ServerName\installation.bat 1>Error.txt 2>&1 
for /f "tokens=*" %%A in ('FIND /i error.txt "Couldn't Access"') do SET Error=%%A
If not x%ERROR:Couldn=%==x%ERROR% (
ECHO Installation Failed.
) Else (
ECHO Installtion complete.  
)
Pause
exit

(Also, notice the use of brackets to make a multi line IF)
the check for if will see if Couldn is part of the string, as a direct comparison will not work, as you would have to check against the whole string including the machine name

Upvotes: 2

Related Questions