Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMD.exe: Get second column output to variable

Tags:

batch-file

cmd

I need the below command second column output <USERNAME> result to variables:

query sessions|find "Active"
>console    <USERNAME>     1   Active

I know the %USERNAME% OR whoami could get the current user name but this script will run using administrator account and will need to be able to capture the current active logon username. If I could select the second column of the output results and assign it to a variable.. this will be a great help.

like image 500
Aaron Ooi Avatar asked Oct 18 '13 06:10

Aaron Ooi


Video Answer


1 Answers

In this case you should use FOR /F to capture the output

for /F "tokens=1,2,3,4,5" %%A in ('"query session | find "Active""') DO (
  echo %%A,%%B,%%C,%%D,%%E
)

It splits also the line at spaces and TABs, but this can be problematic if the username contains spaces.

like image 111
jeb Avatar answered Sep 19 '22 02:09

jeb