0

I would like to read an environment variable called "[TF]MYVAR" via PowerShell. However the following syntax does not work:

$env:[TF]MYVAR

It yields the following error:

Missing or invalid array index expression.

Also adding quitation marks (-> "$env:[TF]MYVAR") does not help.

1 Answer 1

3

The square brackets are confusing the command line parser. Try the alternate variable syntax:

${<variable name>}

See also Get-Help about_Variables.

As @PetSerAl notes below, due to how the command line parser deals with escaping square bracket characters, you'll need to do this:

${env:``[TF``]MYVAR}

You can also use the native .Net methods, which work without needing to be escaped:

[System.Environment]::GetEnvironmentVariable('[TF]MYVAR')
Sign up to request clarification or add additional context in comments.

10 Comments

That will not work. It gets you the value of the variable called env:[TF]MYVAR, but we're looking for the value of the item [TF]MYVAR in the Env: drive. The least verbose thing I found that does that is gc env:'`[TF`]MYVAR', but there ought to be something better.
@JeroenMostert The ${ } syntax has multiple uses in PowerShell. Please read the Get-Help entry for about_Variables under the heading for variables with special characters.
@JeroenMostert To get value of variable env:[TF]MYVAR it need to be ${variable:env:[TF]MYVAR}.
Opening a cmd shell and issuing set [TF]MYVAR=3, then executing powershell and typing ${env:[TF]MYVAR} gives nothing. This is PowerShell 5.1, incidentally. @PetSerAl: well the plot thickens, because yes, that does read the variable, while apparently ${env:[TF]MYVAR} reads... nothing at all.
@BaconBits It need to be ${env:``[TF``]MYVAR} to work properly in that case.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.