Search code examples
batch-filevariablesloggingscoping

Problems with variables when trying to log output


I'm currently working on a batch file, which runs several commands, reads values from text files, etc. The problem I'm facing is that I cannot set variables properly.

The following code snippet demonstrates my problem:

>> %userprofile%\AppData\Local\Temp\test.log 2>&1 (
    echo ### Fetching language...
    powershell -c "(Get-UICulture).Parent.Name" > lang.txt
    set /p LANG=<lang.txt
    echo Your language = %LANG%
)

Output:

### Fetching language...
Your language =

If remove the line >> %userprofile%\AppData\Local\Temp\test.log 2>&1 everything works fine, but the output is not written to a file.

What do I miss here?

Thank you so far!


Solution

  • Your %LANG%-Var is evaluated when the interpreter sees the opening bracket in your first line. This can be disabled this way:

    SETLOCAL ENABLEDELAYEDEXPANSION
    >> %userprofile%\AppData\Local\Temp\test.log 2>&1 (
      echo ### Fetching language...
      powershell -c "(Get-UICulture).Parent.Name" > lang.txt
      set /p LANG=<lang.txt
      echo Your language = !LANG!
      )