67 lines
2.5 KiB
PowerShell
67 lines
2.5 KiB
PowerShell
function Get-EnvironmentVariable {
|
|
<#
|
|
.SYNOPSIS
|
|
Get an environment variable. Will check the supplied store, or if no store supplied, checks all stores in order of process, user, machine.
|
|
|
|
.PARAMETER Name
|
|
Gets the environment variable with the specified name.
|
|
|
|
.PARAMETER StoreName
|
|
Checks the specified store name for the specified name.
|
|
If not present, checks all stores in order of process, user, machine.
|
|
#>
|
|
[CmdletBinding()]
|
|
param(
|
|
[Parameter(Mandatory = $true)]
|
|
[ValidateNotNullOrEmpty()]
|
|
[Alias("Key")]
|
|
[string]$Name,
|
|
[Parameter(Mandatory = $false)]
|
|
[Alias("Store")]
|
|
[Alias("Location")]
|
|
[ValidateSet("Process","User","Machine","Any")]
|
|
[string]$StoreName = "Any"
|
|
)
|
|
|
|
$logLead = Get-LogLeadName
|
|
|
|
Write-Verbose "$logLead : Get environment variable [$Name] from $StoreName store"
|
|
|
|
# Can't combine the three below like we do in Set- and Remove- so we can do the Any fallback
|
|
|
|
if (($StoreName -eq "Any") -or ($StoreName -eq "Process")) {
|
|
$var = [System.Environment]::GetEnvironmentVariable($Name, [system.EnvironmentVariableTarget]::Process)
|
|
if ($null -ne $var) {
|
|
Write-Verbose "$logLead : Found EnvironmentVariable in the Process store"
|
|
return $var
|
|
}
|
|
}
|
|
|
|
if (($StoreName -eq "Any") -or ($StoreName -eq "User")) {
|
|
$var = [System.Environment]::GetEnvironmentVariable($Name, [system.EnvironmentVariableTarget]::User)
|
|
if ($null -ne $var) {
|
|
Write-Verbose "$logLead : Found EnvironmentVariable in the User store"
|
|
return $var
|
|
}
|
|
}
|
|
|
|
if (($StoreName -eq "Any") -or ($StoreName -eq "Machine")) {
|
|
$var = [System.Environment]::GetEnvironmentVariable($Name, [system.EnvironmentVariableTarget]::Machine)
|
|
if ($null -ne $var) {
|
|
Write-Verbose "$logLead : Found EnvironmentVariable in the Machine store"
|
|
return $var
|
|
}
|
|
}
|
|
|
|
# We should not support dotted notation but we do because why not
|
|
# Typically we expect environment variables to use underscores. We should converge on that.
|
|
if ($Name.IndexOf('.') -gt -1) {
|
|
$underscoredName = $Name.Replace('.', '_')
|
|
Write-Verbose "$logLead : Value was not present dotted, will check with underscores for [$underscoredName]"
|
|
|
|
return Get-EnvironmentVariable -Name $underscoredName -StoreName $StoreName
|
|
}
|
|
|
|
Write-Verbose "$logLead : Could not find the key [$Name] in $StoreName store, returning `$null"
|
|
return $null
|
|
} |