3

Using WMIC, I want to get only the drive label based on the drive letter:

for /f "skip=1" %a in ('wmic volume where "Driveletter like '%C%'" get label') do echo %a

Now, those of you who understand Windows command line will see why this doesn't work as expected, because I'm "do"ing an echo. So, using the above, the output looks like the following (which isn't what I'm hoping for):

C:\>for /f "skip=1" %a in ('wmic volume where "Driveletter like '%C%'" get label') do echo %a

C:\>echo System
System

C:\>echo
ECHO is on.

The raw output of the WMIC command looks like the following:

Label
System

The goal is to merely skip the first line (why I was trying to use for /f "skip=1"...) and only get the second line. However, I'm not sure how to merely display this without echoing it.

1
  • Does the solution need to use wmic? I have a PowerShell based solution if that's of help? Commented Mar 7, 2015 at 2:36

3 Answers 3

3

You have two problems. Techie007 identified the first one - You must prefix your DO command with @ if you want to prevent the command from being echoed to the screen. This is not necessary if ECHO is OFF.

The other problem is a very annoying artifact of how FOR /F interacts with the unicode output of WMIC. Somehow the unicode is improperly converted into ANSI such that each line ends with \r\r\n. FOR /F breaks at each \n, and only strips off a single terminal \r, leaving an extra unwanted \r. (Note that \r represents a carriage return character, and \n a newline character)

WMIC output includes an extra empty line at the end. The extra unwanted \r prevents FOR /F from ignoring the line (it is not seen as empty). When you ECHO the value you get ECHO is on.

There are multiple ways to handle this, but my favorite is to pass the output through an extra FOR /F to remove the unwanted \r.

for /f "skip=1 delims=" %a in ('wmic volume where "Driveletter like '%C%'" get label') do @for /f "delims=" %b in ("%a") do @echo %b
1
  • Thank you. I hadn't even noticed the extra carriage return at the end. This works like a champ.
    – Beems
    Commented Mar 9, 2015 at 17:44
1

Prefix Echo with an @ symbol to prevent showing the command.

i.e. (snipped for brevity):

for ... do @echo %a
0

As said by op @dbenham There are multiple ways to handle this:

  • In command-line:
for /f usebackq^tokens^=4delims^=^<^> %G in (`wmic volume where "Driveletter like '%C%'" get label /format:xml ^| find "VALUE"`)do @echo/%G
  • In bat/cmd file:
@echo off

for /f usebackq^tokens^=4delims^=^<^> %%G in (`wmic volume where "Driveletter like '%%C%%'" get label /format:xml ^| find "VALUE"`)do echo/%%G

Change the formatting to xml and the output will change the encode, after that filter to obtain the desired value in one line and on for loop without additional characters and/or linebreaks.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .