Using wmic to get workgroup in a batch file

1

I'm not really versed in batch file, but I am trying to get the workgroup using wmic. I've been trying different things with the for options. So far this is the best result I have gotten.

for /f "skip=1" %%a in ('wmic computersystem get workgroup') do echo %%a

This returns what I want, but it is also echoing something else because it gives an echo is off message. I also want to set the workgroup to a variable such as something like this.

for /f "skip=1" %%a in ('wmic computersystem get workgroup') do set "myVar=%%a"

This doesn't return anything though. I'm assuming I need to use tokens and/or delims, but I just don't have the knowledge to get it to work correctly.

If anyone could assist me on this I would be much appreciated and perhaps it will help me learn a bit more about how to use the for loop. I know this is probably something very simple, so please excuse me for being so ignorant.

BillH

Posted 2017-04-08T16:04:04.030

Reputation: 13

Answers

2

It is also echoing something else because it gives an echo is off

This is because wmic is (badly written and) outputs a blank line at the end of the output.

You can use findstr /r /v "^$" to remove the blank line.

Using a batch file:

@echo off
setlocal
for /f "usebackq skip=1 tokens=*" %%i in (`wmic computersystem get workgroup ^| findstr /r /v "^$"`) do set myVar=%%i
echo %myVar%
endendlocal

Using a command line:

for /f "usebackq skip=1 tokens=*" %i in (`wmic computersystem get workgroup ^| findstr /r /v "^$" ^| findstr /r /v "^$"`) do @set myVar=%i && echo %myVar%

Notes:

  • for /f loops through the wmic output.
  • skip=1 skips the header line (containing VariableValue)
  • findstr /r /v "^$" removes the trailing blank line from the wmic output.

Example output:

> wmic computersystem get workgroup
Workgroup
WORKGROUP


> for /f "usebackq skip=1 tokens=*" %i in (`wmic computersystem get workgroup ^| findstr /r /v "^$" ^| findstr /r /v "^$"`) do @set myVar=%i && echo %myVar%
WORKGROUP

>

Further Reading

DavidPostill

Posted 2017-04-08T16:04:04.030

Reputation: 118 938

This works for what I need. Thank you for the help and the references to help me understand what I am doing. – BillH – 2017-04-08T17:20:52.007