Safely check for a variable’s existence in PowerShell

If you’re needing to access a PowerShell variable, but aren’t guaranteed that the variable has already been declared, you might be looking for a surefire way of finding out. Luckily, the PSProvider that manages the variable store can easily tell you. Simply use the Test-Path cmdlet like so:

if (Test-Path "variable:\VarName")
{
     Write-Host "The variable VarName exists. Its value is $VarName"
}

Note that this can come in handy whether or not you use Strict Mode; Test-Path will return $false for a variable that hasn’t been assigned a value at all, but will report $true if the variable has been explicitly assigned a value of $null. If you were trying to dump the return value of a cmdlet into a variable, for instance, this distinction can sometimes tell you whether the cmdlet ended its execution abnormally.

 

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">