I\'m using PowerShell scripts for some UI automation of a WPF application. Normally, the scripts are run as a group, based on the value of a global variable. It\'s a littl
Personal preference is to use Ignore
over SilentlyContinue
here because it's not an error at all. Since we're expecting it to potentially be $false
let's prevent it (with Ignore
) from being put (albeit silently) in the $Error
stack.
You can use:
if (Get-Variable 'foo' -Scope 'Global' -ErrorAction 'Ignore') {
$true
} else {
$false
}
More tersely:
[bool](gv foo -s global -ea ig)
Output of either:
False
You can trap the error that is raised when the variable doesn't exist.
try {
Get-Variable foo -Scope Global -ErrorAction 'Stop'
} catch [System.Management.Automation.ItemNotFoundException] {
Write-Warning $_
}
Outputs:
WARNING: Cannot find a variable with the name 'foo'.
So far, it looks like the answer that works is this one.
To break it out further, what worked for me was this:
Get-Variable -Name foo -Scope Global -ea SilentlyContinue | out-null
$? returns either true or false.
$myvar = if ($env:variable) { $env:variable } else { "default_value" }