powershellenvironment-variablesindirection

set Windows Enviromental variable with a local powershell variable


I am trying to set and view windows enviromental variables using locally defined variables. Actual code I tried.

   $strAllowGPU_Group   = "TF_FORCE_GPU_ALLOW_GROWTH"
    $strAllowGPU_True   = "True"
    $strUserEnvs        = "User"
    $strCUDAPath =  "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8\bin"
    $strCheckForCUDA = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA"
    $strWhat = $env:${strAllowGPU_Group}
    [System.Environment]::SetEnvironmentVariable(${strAllowGPU_Group},${strAllowGPU_True}, ${strUserEnvs})

I recceive the following error message.

At C:\Users\pgmrdlm\My Drive (pgmrdlm@gmail.com)\DSLR Notes and backup\Software\Scripts\CudaForPixinsight\CudaForPixinsight.ps1:50 char:13

  • $strWhat = $env:${strAllowGPU_Group}
    
  •            ~~~~~ Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to
    

delimit the name. At C:\Users\pgmrdlm\My Drive (pgmrdlm@gmail.com)\DSLR Notes and backup\Software\Scripts\CudaForPixinsight\CudaForPixinsight.ps1:50 char:18

  • $strWhat = $env:${strAllowGPU_Group}
    
  •                 ~~~~~~~~~~~~~~~~~~~~ Unexpected token '${strAllowGPU_Group}' in expression or statement.
    
    • CategoryInfo : ParserError: (:) [], ParseException
    • FullyQualifiedErrorId : InvalidVariableReferenceWithDrive

This works, and it does exactly what I want. Create a persistant windows variable:

[System.Environment]::SetEnvironmentVariable('TF_FORCE_GPU_ALLOW_GROWTH','True', 'User')

I know this is nothing but me not coding the variable names correctly, but I appoligise. I just don't have a clue.

Thank you in advance.

Dan


Solution

  • tl;dr


    Background information:

    Solutions:

    To use variable indirection with environment variables, i.e. to access them via their name being stored in another variable, you must use cmdlets that access the Env: drive:

    Note:


    [1] For the exact rules, see the relevant section of the conceptual "about_Variables" help topic, Variable Names that Include Special Characters

    [2] For more information about PowerShell's namespace variable notation, see this answer.