Aaron Ooi
Aaron Ooi

Reputation: 139

CMD.exe: Get second column output to variable

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.

Upvotes: 9

Views: 13327

Answers (1)

jeb
jeb

Reputation: 82267

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.

Upvotes: 12

Related Questions