1

Here is my script:

echo off
Set "_localState="
Set _localState=YES

if %_localState%==YES (
echo dim answer > %tmp%\tmp.vbs
echo answer=MsgBox("Target Question?",4,"Question") >> %tmp%\tmp.vbs
echo wscript.echo answer >> %tmp%\tmp.vbs
 for /f "delims=" %%a in ('cscript //nologo %tmp%\tmp.vbs') do (
   set ScriptOut=%%a)
   del %tmp%\tmp.vbs
   if %ScriptOut%==6 (
     msg %username% "LOCAL is connected."
 )
)
pause

If I remove outer if condition if %_localState%==YES it will work, but currently not. Where is the problem?

Gerhard
  • 22,678
  • 7
  • 27
  • 43
Inside Man
  • 4,194
  • 12
  • 59
  • 119
  • 1
    @aschipfl, This issue was not caused by delayedexpansion, though it is one of the issues. The issue here was the closing parenthesis inside of the code block. – Gerhard Sep 18 '19 at 06:28
  • 1
    Thanks, @GerhardBarnard, I didn't spot that obviously. I extended the list of duplicates to also cover the parenthesis issue... – aschipfl Sep 18 '19 at 20:01

1 Answers1

1

You need to enable delayed expansion as you are setting and using a variable in a code block, but you are also using parenthesis in a code block, the code is expects the ) after ,"Question" to be the end of the code block, so we need to escape it using cartet ^:

  @echo off
  set "_localState=YES"

  if "%_localState%"=="YES" (
  echo dim answer > %tmp%\tmp.vbs
  echo answer=MsgBox("Target Question?",4,"Question"^)>>"%tmp%\tmp.vbs"
  echo wscript.echo answer>>%tmp%\tmp.vbs
  for /f "delims=" %%a in ('cscript //nologo %tmp%\tmp.vbs') do (
     set "ScriptOut=%%a"
  )
  del %tmp%\tmp.vbs
  setlocal enabledelayedexpansion
  if !ScriptOut! equ 6 (
       msg %username% "LOCAL is connected."    
     )
  endlocal
  )
pause

Also note that I enclose the variables with double quotes in the if ""=="" statements as we need to do a proper comparison and not include accidental whitespace.

Gerhard
  • 22,678
  • 7
  • 27
  • 43