Sometimes I need to know whether a variable has been defined beforehand. This is especially important because I always use “Set-StrictMode -Version 2” and, if I need to use variables from other scopes, I get an error when I try to access a variable that isn’t defined. Although I generally try not to use other scopes, especially $global, sometimes I need them, especially $script.

One example could be wanting to check whether a variable holding an array has been initialized or not, so I can add items to it. The code would look like this:

Function Add-ItemToScriptVariable($item) {
	if (-not (Test-Path variable:script:anyVariable)) {
		[System.Collections.ArrayList]$script:anyVariable = @()
	}
    $script:anyVariable += $item
}

Add-ItemToScriptVariable "item 1"
Add-ItemToScriptVariable "item 2"
Add-ItemToScriptVariable "item 3"

Write-Host $script:anyVariable

As usual in PowerShell, the same command is apparently good for many purposes. In this case, Test-Path lets us check whether a variable exists in a given scope. Even if it feels odd, it’s important to notice that the usual dollar sign doesn’t appear anywhere in this case.

In case anyone is wondering, just like Test-Path works, you can also use the “Get-ChildItem variable:” command. However, if the goal is to list the variables, it’s much more appropriate to use the Get-Variable command.