Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a batch file that checks several of our servers for a user. From the command:

query user %userID% /server:ServerName  

I want to capture the output before it goes to the screen. Is there a way to redirect the output to a variable?

The basic gist of what I want to accomplish is this - we iterate through our servers:

query user %userID% /server:Server1  
query user %userID% /server:Server2  
query user %userID% /server:Server3  
query user %userID% /server:Server4  

Instead of outputting a message that the user could not be found on a specific server, I would like for it to only notify me if it finds the user on a server.

share|improve this question

2 Answers 2

up vote 2 down vote accepted
for /F "tokens=1 delims=" %%i in ('query user %userID% /server:ServerName') do set ans=%%i

If the query user outputs lines before the one that has the data you want, you need to add skip=n where n is the number of lines of output before the one that is interesting to you. Specifying appropriate delimiters for the "delims=" will allow you to have it parsed.

Wouldn't PowerShell be a better way go though?

If the output contains more than one meaningful lines of output the above will only give you the results from the last line. Adding delayed variable substitution and compound commands after the "do" by enclosing them in () could allow you handle that.

Or you could redirect the output to a file query user %UserID% /user:ServerN >ServerN.txt and then parse that with a for /f ...

share|improve this answer
    
@Andrew: unfortunately I'm stuck with what they give me - I'm sure PowerShell would be much better. So, if I understand correctly, I will implement the for /F "... /server:... for each server I have. I should be able to parse the return value in ans to check for successful search. I'm not sure what to place in the delims field, though. –  IAbstract Apr 27 '10 at 13:19

The best way to figure out what to put the delims is by piping the output to a file and inspecting the output in an editor. A space is likely. so the just make sure that in the options delims= is last, if you leave a space for before the closing quote, then you will get spaces as a delimiter. You'll then want to likely then specify the tokens as well. For example if you want the 1st 3rd and 4th fields delimited by a space the options would be "tokens=1,3,4 delims= " To access those you pull them out of %%i, %%j and %%k.

share|improve this answer
    
@Andrew: Delete this answer and edit it to the bottom of your previous answer... ;) –  IAbstract Apr 27 '10 at 14:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.