windows 如何将主机名存储在 .bat 文件中的变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/998366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:29:25  来源:igfitidea点击:

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

windowsbatch-filescriptinghostname

提问by Edward Q. Bridges

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

我想将此/bin/sh语法转换为广泛兼容的 Windows 批处理脚本:

host=`hostname`
echo ${host}

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

如何做到这一点,以便它可以在任何 Windows Vista、Windows XP 和 Windows 2000 机器上运行?

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.

澄清一下:然后我想继续执行程序并使用存储在变量中的主机名host。换句话说,该程序的更大目标不是简单地回显主机名。

回答by sean e

hmm - something like this?

嗯——像这样的?

set host=%COMPUTERNAME%
echo %host%

EDIT: expanding on jitter's answer and using a technique in an answer to this questionto 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.

在任何一种情况下,'host' 都是作为环境变量创建的。

回答by Dave Webb

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

我通常使用FOR命令将命令输出读入变量,因为它不必创建临时文件。例如:

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 FORstatement by putting them twice:

请注意,上述语句将在命令行上工作,但在批处理文件中无效。要在批处理文件中使用它逃脱%FOR通过把他们两次声明:

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 FORat command prompt.

您还可以使用FOR. 有关更多详细信息,只需HELP FOR在命令提示符下键入。

回答by brakertech

I'm using the environment variable COMPUTERNAME:

我正在使用环境变量COMPUTERNAME

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

回答by maniattico

Why not so?:

为什么不这样?:

set host=%COMPUTERNAME%
echo %host%

回答by jitter

Just create a .bat file with the line

只需使用该行创建一个 .bat 文件

hostname

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

在里面。就是这样。Windows 还支持主机名命令。

回答by Ariful Huq

 set host=%COMPUTERNAME%
 echo %host%

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

这个就够了。不需要额外的大编码循环。