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
EDIT: Use stej's answer below. My own (partially incorrect) one is still reproduced here for reference:
You can use
Get-Variable foo -Scope Global
and trap the error that is raised when the variable doesn't exist.
Simple: [boolean](get-variable "Varname" -ErrorAction SilentlyContinue)
There's an even easier way:
if ($variable)
{
Write-Host "bar exist"
}
else
{
Write-Host "bar does not exists"
}
You can assign a variable to the return value of Get-Variable then check to see if it is null:
$variable = Get-Variable -Name foo -Scope Global -ErrorAction SilentlyContinue
if ($variable -eq $null)
{
Write-Host "foo does not exist"
}
# else...
Just be aware that the variable has to be assigned to something for it to "exist". For example:
$global:foo = $null
$variable = Get-Variable -Name foo -Scope Global -ErrorAction SilentlyContinue
if ($variable -eq $null)
{
Write-Host "foo does not exist"
}
else
{
Write-Host "foo exists"
}
$global:bar
$variable = Get-Variable -Name bar -Scope Global -ErrorAction SilentlyContinue
if ($variable -eq $null)
{
Write-Host "bar does not exist"
}
else
{
Write-Host "bar exists"
}
Output:
foo exists
bar does not exist
Test the existence of variavle MyVariable. Returns boolean true or false.
Test-Path variable:\MyVariable
Test-Path can be used with a special syntax:
Test-Path variable:global:foo
This also works for environment variables ($env:foo
):
Test-Path env:foo
And for non-global variables (just $foo
inline):
Test-Path variable:foo