In PowerShell, how do I test whether or not a specific variable exists in global scope?
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 little inconvenient to set this variable manually for the times when I want to run just one script, so I'm looking for a way to modify them to check for this variable and set it if not found.
test-path variable:\foo doesn't seem to work, since I still get the following error:
The variable '$global:foo' cannot be retrieved because it has not been set.
Solution 1:
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
Solution 2:
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.