tags:

views:

82

answers:

4

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.

A: 

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.

Scott A. Lawrence
+2  A: 

You can use

Get-Variable foo -Scope Global

and trap the error that is raised when the variable doesn't exist.

Joey
+9  A: 

Test-Path can be used with a special syntax:

Test-Path variable:global:foo
stej
+1 for the very clever use of the variable PsProvider
Cédric Rup
Thx ;) imo that's the correct way, no such workaround like `-ErrorAction SilentlyContinue` or `try/catch` with `Get-Variable`.
stej
Ah, nice one. Why do I even bother with PS questions ;-). I can't delete my answer anymore, though.
Joey
Because cmd.exe is boring :) No need to delete, it's ok to have all possible answers for inspiration.
stej
A: 

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
George Howarth