如何在批处理文件中使用命令SET查找从PowerShell函数返回的子字符串?

问题描述 投票:0回答:1

我在批处理文件中调用了.ps1函数,并将结果分配给$Value变量:

for /f "delims=" %%a in ('powershell -ExecutionPolicy Bypass .\test.ps1 -TargetGroupArn "arn:aws:elasticloadbalancing:eu-west-1:570226278193:targetgroup/whocms-uat/cc28ab2765d2503c" -TargetId "i-01fab6896b4efa925" -state "healthy" -timeout 240') do Set "$Value=%%a"

使用echo检查时,它会输出正确的结果:09/13/2018 16:34:34 : healthy

Echo Value received from PowerShell : %$Value%

但我无法检查结果是否包含子字符串:

set str1=%Value%
if not x%str1:healthy=%==x%str1% echo It contains healthy
windows powershell batch-file cmd substring
1个回答
2
投票

解决方案非常简单:

if not "%$Value:healthy=%" == "%$Value%" echo It contains healthy

运算符==之间的两个字符串参数的双引号导致通过IF将"之间的所有内容解释为文字字符。否则,值字符串内的空格将被解释​​为参数分隔符。

IF包括比较两个字符串的双引号。这意味着在使用"..."作为一个参数时,"..."也必须用于其他参数,否则两个比较的字符串永远不会相等。

有关IF如何比较字符串或整数的更多详细信息,请参阅Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files上的答案。

PS:$对于在环境变量名中使用的Windows命令处理器没有特殊意义。它被解释为像字母一样的文字字符。

© www.soinside.com 2019 - 2024. All rights reserved.