0

I hope someone can help :)

I'm trying

  • to get the output of a WMIC query into a variable
  • to manipulate this variable by deleting the last char (colon)
  • to reuse this remaining char in my script

This is the line which generates the value I need to work with:

for /f "skip=1" %%A in ('wmic logicaldisk where "Description='Removable Disk'" get name') do

Usually, the output looks like this:

E:

Now I need to cut this variable to get the driveletter "E" only, which I need to reuse in my script.

I found this threat which I expected to be the solution for my problem too. Unfortunately this doesn't work for me since the output is completely empty applying this.

I think I'm doing something wrong when writing the output the %%A into a variable.

My code currently looks like this:

@ECHO OFF
for /f "skip=1" %%A in ('wmic logicaldisk where "Description='Removable Disk'" get name') do (
echo.%%A
set drive=%%A
set drive=%drive:~0,-1%
echo.%drive%
)

Output of this code is:

E:
:*:
:*:

Does somebody know what I'm doing wrong? :)

Thank you in advance for any help!

  • use `%drive:~0,1%` here. `WMIC` has a non-standard line ending, wich results in a variable ending with `` – Stephan Jan 25 '18 at 10:25
  • Hi @Stephan, thank you for your quick reply :) Now the output is (line by line) `E: ~ ~ ` – 3dij223 Jan 25 '18 at 11:06
  • 1
    If you insist on using that method, then delayed expansion will certainly help. – Compo Jan 25 '18 at 11:22
  • `E: ~ ~ ` is because `wmic` outputs 4 lines. You skip the first, the second one is your "payload" and then there are two (apparently empty) lines. The problem is, for the eye of the command interpreter they are *not* empty, but contain a ``. In my answer I avoid them to be processed, because they don't have a second token (one of several possibilities). – Stephan Jan 25 '18 at 13:52
  • This is just a note to mention that, there's no guarantee that USB drives will be registered as `Removable Disk`. – Compo Jan 25 '18 at 14:22
  • Thank you for this hint Compo! – 3dij223 Jan 26 '18 at 06:51

1 Answers1

1

there are many different methods to work around wmic's ugly line endings. In your case, it's relatively easy (you even don't need any variables):

for /f "skip=1 tokens=2 delims==:" %%A in ('wmic logicaldisk where "DriveType='2'" get name /value') do echo %%A

I switched from Description='Removable Disk' to DriveType='2', because output is language dependent (in German, it's Description=Wechseldatenträger) and 2 is 2 in every language.

Stephan
  • 53,940
  • 10
  • 58
  • 91