0

I've called .ps1 function in batch file and assigned the result to $Value variable:

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"

When checked with echo it prints the correct result: 09/13/2018 16:34:34 : healthy

Echo Value received from PowerShell : %$Value%

But I am not able to check if the result contains substring:

set str1=%Value%
if not x%str1:healthy=%==x%str1% echo It contains healthy
Mofi
  • 46,139
  • 17
  • 80
  • 143
  • 2
    You need to surround your string comparisons in double quotes to protect spaces and special characters. `if not "x%str1:healthy=%"=="x%str1%" echo It contains healthy` – Squashman Sep 13 '18 at 14:37
  • Why can you not use `-match "healthy"` in your PowerShell command, instead of running it in a `For` loop, saving the output as a variable, then expanding/replacing the string in the variable to determine if it was part of the output? – Compo Sep 13 '18 at 15:47
  • 1
    Should also note that you missed using the dollar symbol with your variable name in the`set` command. – Squashman Sep 13 '18 at 16:48
  • 1
    With surrounding quotes the leading `x` is no longer necessary to be safe against empty values... – aschipfl Sep 13 '18 at 17:26

1 Answers1

2

The solution is quite simple:

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

The double quotes around the two string arguments between the operator == results in interpreting everything between " as literal characters by IF. Otherwise a space inside value string is interpreted as argument separator.

IF includes the double quotes on comparing the two strings. This means on using "..." for one argument, "..." must be also used on other argument as otherwise the two compared strings are never equal.

For even more details on how IF compares strings or integers see the answer on Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files.

PS: $ has no special meaning for Windows command processor on being used in an environment variable name. It is interpreted as literal character like a letter.

Mofi
  • 46,139
  • 17
  • 80
  • 143