Option 1
You can do this with:
$x = 'RiskScheduler'
Write-Host (Get-Item env:$x).Value
Which will output true
in your case
If you have a list of variable names:
$varNames = @('COMPUTERNAME', 'SESSIONNAME', 'RiskScheduler')
ForEach($varName in $varNames) {
Write-Host (Get-Item env:$varName).Value
}
Which will output:
MyPcName
Console
true
You can find more information about this by entering Get-Help about_environment_variables
into PowerShell:
Get-Item -Path Env:* | Get-Member
Displaying Environment Variables
You can use the cmdlets that contain the Item noun (the Item cmdlets) to
display and change the values of environment variables. Because
environment variables do not have child items, the output of Get-Item
and Get-ChildItem is the same.
When you refer to an environment variable, type the Env: drive name
followed by the name of the variable. For example, to display the value
of the COMPUTERNAME environment variable, type:
Get-Childitem Env:Computername
Option 2
Another option would be to use this function:
function Get-EnvVar($Name) {
$allVars = dir env:
foreach ($var in $allVars) {
If ($var.Name -eq $Name) {
return $var
}
}
}
The function iterates around all available environment variables and returns the one you are after (in this case, $Env:COMPUTERNAME
).
You can then call
Write-Host $myvar.Value
to display the value of COMPUTERNAME
If you have an array of variable names you want the value of:
$varNames = @('COMPUTERNAME', 'SESSIONNAME', 'RiskScheduler')
ForEach($varName in $varNames) {
$var = Get-EnvVar -Name $varName
Write-Host $var.Value
}
Which outputs (for me) :
MyPcName
Console
true
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…