如何将主机名存储在 .bat 文件中的变量中? [英] How to store the hostname in a variable in a .bat file?

查看:44
本文介绍了如何将主机名存储在 .bat 文件中的变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

host=`hostname`
echo ${host}

如何做到这一点才能在任何 Windows Vista、Windows XP 和 Windows 2000 机器上运行?

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

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

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.

推荐答案

我通常使用 FOR 命令将命令输出读入变量中,因为这样可以省去创建临时文件的麻烦.例如:

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

注意,上面的语句可以在命令行中使用,但不能在批处理文件中使用.要在批处理文件中使用它,将 % 放在 FOR 语句中,将它们放置两次:

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%

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

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

这篇关于如何将主机名存储在 .bat 文件中的变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆