Home > Back-end >  how to assign output from command to variable in command prompt
how to assign output from command to variable in command prompt

Time:04-11

I have these two commands

C:\Users\xyz\AppData\Local\Temp>WMIC LOGICALDISK where volumename="abc" get deviceid>%temp%/path.txt

which creates file path.txt with content:

DeviceID
F:      

the file has lots of additional spaces which I have added in the above file^

I then use (although I know I could use the | char I am trying to avoid it) the command C:\Users\xyz\AppData\Local\Temp>FINDSTR [:] path.txt>path2.txt which gives the output F : which is incredibly frustrating as I obviously just need the "F"/alphabetic char that would be in its position and store it in a variable.

Could someone please show me how to do this - or ultimately get the drive letter of a usb device using cmd only and store it in a variable?

I don't mind if it takes a lot of lines just no | char please or quote marks " :)

edit: it MUST be in command prompt and can be written line by line (no cop and paste commands) and I need the individual letter (eg. F:) by itself - stored in a variable or the clip board. and obviously, no pipe character or quote marks pls :)

CodePudding user response:

No | char please :) I think you mean the pipe character | (U 007C, Vertical Line)?

Batch file (set a desired string to the _volume variable instead of my debugging value Elements):

@ECHO OFF
@SETLOCAL
rem set the variable _volume and delete the variable _letter
set "_volume=Elements"
set "_letter="

for /F "tokens=2 delims==:" %%G in ('
  WMIC LOGICALDISK where volumename^="%_volume%" get deviceid/Value
') do set "_letter=%%G"

echo letter of volume "%_volume%" is "%_letter%"    

Output: .\SO\71753240.bat

letter of volume "Elements" is "F"

Command prompt (copy and paste the following code snippet into an open cmd.exe window):

set "_volume=Elements"
set "_letter="
for /F "tokens=2 delims==:" %G in ('WMIC LOGICALDISK where volumename^="%_volume%" get deviceid/Value') do @set "_letter=%G"
@echo letter of volume "%_volume%" is "%_letter%"    

Note that wmic output redirected to a file is UTF-16-BOM:

WMIC LOGICALDISK where volumename="%_volume%" get deviceid>%temp%\path71753240.txt
hexdump.exe -H %temp%\path71753240.txt
000000  ff fe 44 00 65 00 76 00 69 00 63 00 65 00 49 00  ..D.e.v.i.c.e.I.
000010  44 00 20 00 20 00 0d 00 0a 00 46 00 3a 00 20 00  D. . .....F.:. .
000020  20 00 20 00 20 00 20 00 20 00 20 00 20 00 0d 00   . . . . . . ...
000030  0a 00
  • Related