根据字符串比较输出执行不同的命令



我有一个字符串,例如-"xxxxxxx New State"(其中xxx-服务器的主机名),如果主机名包含nb,我需要在其上执行某个命令;如果主机名不包含字母'nb',我需要执行某组其他命令(它只会在主机名字符串中出现一次)。

这是我现在拥有的:-

set Hostname="xxxxxxx New State"
echo %Hostname%|findstr /I "nb" > null
If "%errorlevel%"=="0" Goto Found
If "%errorlevel%"=="1" Goto NotFound
:Found
 some commands..
 :NotFound
 Some commands..

但这是行不通的。我也使用了if-else语句,但效果不太好!

如需进一步澄清有关要求,请告诉我。

-Abhi

试试这个:

set Hostname="xxxxxxx New State"    
echo %Hostname%|findstr /I "nb" >nul && goto Found || goto NotFound
goto :eof
:Found    
echo found it
{other commands}
goto :AnotherLabel
:NotFound
echo didn't find it
{other commands}
goto :AnotherLabel
:AnotherLabel
{do more stuff...}

如果第一个命令成功,则双安培数&&将运行以下命令。如果第一个命令不成功,则双管||将运行以下命令。

以下是描述这些(以及其他)重定向符号的一个来源。

@Aacini提出了一种更简单的方法:

set Hostname="xxxxxxx New State"
rem If `%Hostname%` contains "nb" then the first expansion removes 
rem it, so the result is different from itself.
if "%Hostname:nb=%" neq "%Hostname%" goto Found. 
rem if the above statement is false, it will do these next commands
rem so there is no need for a :NotFound label
echo didn't find it
{other commands}
goto :AnotherLabel
:Found
echo found it
{other commands}
:AnotherLabel
...

最新更新