windows cmd中的计算机名变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18713118/
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 10:51:56  来源:igfitidea点击:

Computername variable in cmd

windowsvariablescmd

提问by Stefan Frederiksen

In CMD the following variable will give you the name of the computer: %COMPUTERNAME%

在 CMD 中,以下变量将为您提供计算机的名称:%COMPUTERNAME%

I need a variable that takes a part of the computername.

我需要一个包含计算机名一部分的变量。

I need a if statement that checks if the computername contains "KM" at the start and 00 at the end. It should not look at the number between KM and -00

我需要一个 if 语句来检查计算机名是否包含开头的“KM”和结尾的 00。它不应该看KM和-00之间的数字

KM100-00
KM200-00

回答by foxidrive

This works here:

这在这里工作:

echo %computername%| findstr "^KM.*00$" >nul && echo found the right format

回答by paxdiablo

You can do this with substring commands, as per the following transcript:

您可以使用子字符串命令执行此操作,如以下脚本所示:

pax> set xyzzy=KM100-00 KM200-00

pax> echo %xyzzy%
KM100-00 KM200-00

pax> echo %xyzzy:~0,2%
KM

pax> echo %xyzzy:~-2,2%
00

pax> if %xyzzy:~0,2%==KM if %xyzzy:~-2,2%==00 echo yes
yes

That final (chained) ifstatement is the one you're looking for to see if your variable starts with KMand ends with 00.

最后的(链式)if语句是您要查看变量是否以 开头KM和结尾的语句00

The expression %X:~Y,Z%will give you the Zcharacters starting at position Y(zero-based) of the variable X. You can provide a negative value of Yto make it relative to the end of the string.

该表达式%X:~Y,Z%将为您提供从变量的Z位置Y(从零开始)开始的字符X。您可以提供一个负值Y以使其相对于字符串的末尾。

回答by npocmaka

echo %computername%| findstr /I /b "KM" | findstr /i /e "00" && echo computer name is like KM-XX-00

You can try also with hostnameinstead of echo %computername%

您也可以尝试使用hostname代替echo %computername%

回答by Sarge

I recommend you to read this page, which is about substring usage in command prompt.

我建议你阅读这个页面,它是关于命令提示符中子字符串的使用。

And why dont you try this;

你为什么不试试这个;

set str=KM2000-00
echo.%str%

set pre=%str:~0,2%
echo.%pre%

set pst=%str:~-2%
echo.%pst%

IF %pre% == KM( IF %pst% == 00( echo.true ) )

pause