Determining whether a variable exists before attempting to use it is helpful when writing scripts. However, if you look at the PowerShell cmdlets, you won't find a cmdlet devoted solely to this task. The reason is that PowerShell doesn't need one. It already has a more general cmdlet named Test-Path that does this as well as several other tasks.

Working with files and folders has always been a major part of administrative scripting, and checking whether a particular file or folder exists is frequently part of solutions. It's so common that PowerShell provides the Test-Path cmdlet to test whether a particular file or folder exists. For example, to see whether the bootsect.bak file exists on the root of the local C drive, you'd run the command

Test-Path -Path c:\bootsect.bak

This command returns True if C:\bootsect.bak exists and False if it doesn't. Similarly, to see whether the Windows folder exists on the root of the local C drive, you'd use the command

Test-Path -Path c:\windows

Files and folders aren't the only items that have paths in the PowerShell environment. The PowerShell drives expose all sorts of items, including variables, registry keys, functions, aliases, and certificates. All these items have paths, so you can use Test-Path to check for their existence.

To see all of the currently available drives in your system, you can run the cmdlet

Get-PSDrive

Figure 1 shows sample results.

PowerShellGetPS-Drivecmdlet103682Fig1

Notice the drives named Variable and Env. The Variable drive gives you a path you can use to access variables currently defined in the PowerShell environment. For example, if you want to test whether a variable named ofs exists, you'd use the command

Test-Path variable:\ofs

The Env drive contains environment variables inherited from the Windows shell environment. For example, to see whether the environment variable %temp% is defined, you'd run the command

Test-Path env:\temp

Get-PSDrive also exposes the Function drive and two registry drives. The Function drive lets you access PowerShell’s functions the same way you would files and folders. For example, to test for the built-in PowerShell function named more, you'd use

Test-Path Function:\more

The exposed registry drives are HKLM and HKCU. So, for example, to find out whether there's a registry key HKEY_LOCAL_MACHINE\Software, you'd run

Test-Path HKLM:\Software

The Test-Path cmdlet demonstrates the value behind PowerShell's "everything is a path" concept. Instead of having to use different tools to test for the existence of folders, files, registry keys, and other items like you do with VBScript and other traditional Windows-based scripting languages, you can simply use one tool (and one syntax) to test every item on any PowerShell drive. This lets you concentrate on using the results instead of worrying about how to get them.