Batch findstr return only field value

Viewed 195

How can I return only the value field from a command in batch? For example:

ipconfig /all | findstr "Host Name"

Will return

Host Name . . . . . . . . . . . . : YOUR_HOSTNAME

But I only want the value. In this case, YOUR_HOSTNAME.

Also, if there are more than one line, it should get the first match from the top.

3 Answers
for /f "tokens=1*delims=:" %b in ( 'ipconfig /all ^| findstr /c:"Host Name"') do set "hostname=%c"
set "hostname=%hostname:~1%"

from the prompt. Change %b and %c to %%b and %%c to use within a batch file.

The caret escapes the pipe, telling cmd that the pipe is part of the command to be executed, not of the for.

The /c:"Host Name" makes findstr find the precise string Host Name. As you have it, findstr would find either Host or Name, which would deliver a hit on

Ethernet adapter VirtualBox Host-Only Network:
   Description . . . . . . . . . . . : VirtualBox Host-Only Ethernet Adapter

for instance.

To force the first match, append &goto label to the for command line and insert :label between the two lines in a batch file.

If you want the hostname, Windows already provides a program to give exactly that without any string parsing.

"%__APPDIR__%HOSTNAME.EXE"

Use it in a batch-file to set a variable.

FOR /F "delims=" %%A IN ('"%__APPDIR__%HOSTNAME.EXE"') DO (SET "THISHOST=%%~A")
ECHO THISHOST IS %THISHOST%

If you want to step up to .Net or PowerShell, there is:

[System.Net.Dns]::GetHostName()

Then, you would not believe this, but there is an environment variable called %computername%

Try it yourself:

echo %computername%
Related