Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PowerShell, how do I test whether or not a specific variable exists in global scope?

Tags:

powershell

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.

like image 568
Scott Lawrence Avatar asked Jul 01 '10 16:07

Scott Lawrence


People also ask

How do I check environment variables in PowerShell?

Environment] to retrieve the specific or all environment variables. To retrieve all environment variables use GetEnvironmentVariables() class. To get the specific environment variable using . Net method use GetEnvironmentVariable() method.

How do you access global variables in PowerShell?

To declare a PowerShell global variable, simply use the below syntax. $global: myVariable ="This is my first global variable." If you choose not to give any value to it, you can explicitly assign a null value to it.

Are variables scoped in PowerShell?

PowerShell scope protects variables and other artifacts by limiting where they can be read and modified. Scope levels protect items that should not be changed. PowerShell has the following scopes available: Global: This scope is available when you open a PowerShell console or create a new runspace or session.

How do you echo a variable in PowerShell?

The echo command is used to print the variables or strings on the console. The echo command has an alias named “Write-Output” in Windows PowerShell Scripting language. In PowerShell, you can use “echo” and “Write-Output,” which will provide the same output.


2 Answers

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 
like image 184
stej Avatar answered Sep 21 '22 18:09

stej


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.

like image 28
Joey Avatar answered Sep 17 '22 18:09

Joey