How to store the hostname in a variable in a .bat file?

WindowsBatch FileScriptingHostname

Windows Problem Overview


I would like to convert this /bin/sh syntax into a widely compatible Windows batch script:

host=`hostname`
echo ${host}

How to do this so that it'll work on any Windows Vista, Windows XP, and Windows 2000 machine?

To clarify: I would then like to go on in the program and use the hostname as stored in the variable host. In other words, the larger goal of the program is not to simply echo the hostname.

Windows Solutions


Solution 1 - Windows

hmm - something like this?

set host=%COMPUTERNAME%
echo %host%

EDIT: expanding on jitter's answer and using a technique in an answer to this question to set an environment variable with the result of running a command line app:

@echo off
hostname.exe > __t.tmp
set /p host=<__t.tmp
del __t.tmp
echo %host%

In either case, 'host' is created as an environment variable.

Solution 2 - Windows

I usually read command output in to variables using the FOR command as it saves having to create temporary files. For example:

FOR /F "usebackq" %i IN (`hostname`) DO SET MYVAR=%i

Note, the above statement will work on the command line but not in a batch file. To use it in batch file escape the % in the FOR statement by putting them twice:

FOR /F "usebackq" %%i IN (`hostname`) DO SET MYVAR=%%i
ECHO %MYVAR%

There's a lot more you can do with FOR. For more details just type HELP FOR at command prompt.

Solution 3 - Windows

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

Solution 4 - Windows

Why not so?:

set host=%COMPUTERNAME%
echo %host%

Solution 5 - Windows

Just create a .bat file with the line

hostname

in it. That's it. Windows also supports the hostname command.

Solution 6 - Windows

 set host=%COMPUTERNAME%
 echo %host%

This one enough. no need of extra loops of big coding.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdward Q. BridgesView Question on Stackoverflow
Solution 1 - Windowssean eView Answer on Stackoverflow
Solution 2 - WindowsDave WebbView Answer on Stackoverflow
Solution 3 - WindowsbrakertechView Answer on Stackoverflow
Solution 4 - WindowsmaniatticoView Answer on Stackoverflow
Solution 5 - WindowsjitterView Answer on Stackoverflow
Solution 6 - WindowsAriful HuqView Answer on Stackoverflow