How to save hostname in variable in .bat file?

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

 host=`hostname` echo ${host} 

How to make it work on any Windows Vista, Windows XP, and Windows 2000 machine?

To clarify: I would like to continue working in the program and use the host name stored in the host variable. In other words, the big goal of the program is not just an echo host name.

+44
windows scripting batch-file
Jun 15 '09 at 21:00
source share
6 answers

I usually read the output of a command into variables using the FOR command, since it saves the need 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 the batch file. To use it in a batch file, open % in the FOR statement, setting them twice:

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

With FOR you can do much more. For more details, just type HELP FOR at the command line.

+51
Jun 15 '09 at 21:53
source share

hmm - something like this?

 set host=%COMPUTERNAME% echo %host% 

EDIT : extending the jitter response and using the method in answering this question to set an environment variable with the result of running the command line application:

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

In any case, "host" is created as an environment variable.

+53
Jun 15 '09 at 21:07
source share

I use the COMPUTERNAME environment variable:

 copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32 srvcheck \\%COMPUTERNAME% > c:\shares.txt echo %COMPUTERNAME% 
+10
Sep 20 2018-10-18
source share

Why not?:

 set host=%COMPUTERNAME% echo %host% 
+5
Feb 17 '10 at 11:44
source share

Just create a .bat file with line

 hostname 

. It. Windows also supports the hostname command.

+1
Jun 15 '09 at 21:07
source share
  set host=%COMPUTERNAME% echo %host% 

It's enough. no need for extra large coding cycles.

0
Jan 23 '19 at 6:49
source share



All Articles