91

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.

0

10 Answers 10

260

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
8
  • Thx ;) imo that's the correct way, no such workaround like -ErrorAction SilentlyContinue or try/catch with Get-Variable.
    – stej
    Jul 2, 2010 at 14:20
  • 7
    I used this concept, but in my case I had to test for variable:local:foo Mar 10, 2014 at 22:53
  • 5
    If the variable is not global, make sure to not include the "global" part. May 12, 2016 at 15:39
  • This doesn't seem to work when I test for a parameter given on the command line. param([string]$name) <CR>test-path global:variable:name i get back False. Is a parameter not a variable? I also tried local:variable and (global|local):parameter.
    – Dan Pritts
    May 19, 2016 at 20:02
  • 2
    Would someone mind providing the documentation for this syntax?
    – Josh Gust
    Feb 1, 2019 at 16:17
28

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.

9
  • 3
    I'd personally go with stej's answer; I commented so on it and I upvoted it as well. I just cannot remove this one anymore.
    – Joey
    Aug 6, 2013 at 15:31
  • 2
    I wouldn't. This answer is more specific to the action that's occurring, improving code readability.
    – VertigoRay
    Nov 13, 2015 at 17:35
  • @VertigoRay: Using exceptions as control-flow mechanisms always has a bit of a bad smell to me. Yes, historically you've been forced to do that in shell languages but that doesn't make it a particular good idea. In this case you want to check for existence of a variable. Test-Path on the Variable provider does exactly that. Get-Variable gives you the value or an error.
    – Joey
    Nov 14, 2015 at 12:28
  • 4
    You don't have to trap the error. Get-Variable foo -Scope Global -ErrorAction SilentlyContinue works just fine. For example: if (Get-Variable foo -Scope Global -ErrorAction SilentlyContinue) { $true } else { $false } will output: False
    – VertigoRay
    Nov 18, 2015 at 23:16
  • I posted another solution that encumpasses what I'm talking about.
    – VertigoRay
    Nov 18, 2015 at 23:24
23

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

Alternatively

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'.
3
  • 2
    Agree: Since you're checking for it, it's not an error. Should be "Ignore"d.
    – JoePC
    Feb 20, 2019 at 17:38
  • Doesn't work on $input
    – dns
    Jul 26 at 21:50
  • It doesn't work the way you're expecting on $input. The problem is that $input is an Automatic Variable, so it's always set.
    – VertigoRay
    Jul 27 at 22:41
7

Simple:

 [boolean](get-variable "Varname" -ErrorAction SilentlyContinue)
4

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
2
$myvar = if ($env:variable) { $env:variable } else { "default_value" } 
1
  • This does not work if the $env:variable is explicitly set to false.
    – citelao
    Mar 10, 2020 at 18:18
2

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.

1
  • Further along in that thread, they mention that Test-Path variable:global:foo will work, as per stej's answer. Mar 7, 2012 at 23:54
1

You can try:

$global:foo -eq $null

This will return $true if the $global:foo is not set.

-1

Test the existence of variavle MyVariable. Returns boolean true or false.

Test-Path variable:\MyVariable

-5

There's an even easier way:

if ($variable)
{
    Write-Host "bar exist"
}
else
{
    Write-Host "bar does not exists"
}
1
  • 8
    What if $variable does exist, but equal to $false? Mar 10, 2014 at 22:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.