# The target environment variable.
$env:Pokemon='bingo!'
# The variables that, in combination, return the *name*
# of the target environment variable.
$env:a = 'Poke'
$env:b = 'mon'
# Use Get-Content and the env: drive to retrieve
# an environment variable by an *indirectly* specified name.
# Note:
# * env:$env:a$env:b is treated like "env:$env:a$env:b",
# i.e. an expandable (interpolating string).
# * For better visual delineation of the variables, use:
# env:${env:a}${env:b}
# * `-ErrorAction Ignore` ignores the case when the target var.
# doesn't exist (quietly returns $null`)
# -> 'bingo!'
Get-Content -ErrorAction Ignore env:$env:a$env:b
# Alternative, with explicit string concatenation.
Get-Content -ErrorAction Ignore ('env:' + $env:a + $env:b)
1条答案
按热度按时间cwtwac6a1#
基于有用的评论:
您正在寻找 * 间接 *,即通过 * 另一个 *(环境)变量(存储目标变量的 * 名称 ) 间接 * 引用环境变量的能力。
将
Env:
drive与Get-Content
cmdlet结合使用:注:
Set-Content
cmdlet;例如:variable:
驱动器,或者为了更灵活,使用Get-Variable
和Set-Variable
cmdlet-请参见this answer。"env:$env:a$env:b"
等可扩展(插值)字符串文字的详细信息,请参阅概念性about_Quoting帮助主题。正如Max所指出的,您还可以使用静态
System.Environment.GetEnvironmentVariable
. NET方法:有关从PowerShell调用. NET API方法的详细信息,请参阅概念性的about_Methods帮助主题。