powershellstring-literals

Powershell, write creation of environment variables to file


I have a simple question I am struggling to find answer to. I want to write next: "$env:CI_JOB_STAGE = preprocessing" to a file.

I tried with this:

Add-Content -Path test.bat -Value "$env:CI_JOB_STAGE = preprocessing"

What i receive in file is:

 = preprocessing

Thats because I dont have this variable created yet but I want it to be created later when the file will be executed.

What I want to get in the file is:

$env:CI_JOB_STAGE = preprocessing

Solution

  • Variables expand in a string with double-quotes "...", use single-quotes instead '...'. See about_Quoting_Rules for more details.

    Add-Content -Path test.bat -Value '$env:CI_JOB_STAGE = "preprocessing"'
    

    The article linked above also explains that if you need to use double-quotes you can escape the variable expansion using a backtick (`):

    Add-Content -Path test.bat -Value "`$env:CI_JOB_STAGE = 'preprocessing'"