Home » PowerShell » Check PowerShell Variable Exists

Check PowerShell Variable Exists

In PowerShell, the Test-Path cmdlet is used to check variable exists or not. Verifying the existence of variables is important to avoid errors in the script and maintain stability in the script.

In this article, we will discuss how to check in a PowerShell variable exists by using Test-Path, and Get-Variable cmdlets.

Use Test-Path to Check PowerShell Variable Existence

Use the Test-Path cmdlet in PowerShell to check variable existence.

$variableExists = Test-Path -Path Variable:\filePath

The above PowerShell script uses the Test-Path cmdlet for checking variable existence. The command use Variable: provider to check if a variable exists.

The output of the above PowerShell script returns either a True or False value.

PS D:\> $variableExists = Test-Path -Path Variable:\filePath                                                            PS D:\> $variableExists                                                                                                 
True
PS D:\>    

Use Get-Variable To Check Variable Existence

The Get-Variable cmdlet in PowerShell can be used to check variable existence.

$variableExists = (Get-Variable -Name filePatha -ErrorAction SilentlyContinue) -ne $null

In the above PowerShell script, the Get-Variable cmdlet uses the Name parameter to specify the variable name and uses the ErrorAction parameter to run the script silently even if the error occurs.

The output of the above script returns either a True or False value.

PS D:\> $variableExists = (Get-Variable -Name filePath -ErrorAction SilentlyContinue) -ne $null                         

PS D:\> $variableExists                                                                                                 
True
PS D:\>    

Cool Tip: How to check if a variable is null or empty in PowerShell!

Use If Statement to Check if Variable Exists

Using an If statement to check if a variable exists in the PowerShell session is another option.

if ($filePath -ne $null) {
    Write-Host "Variable exists"
} else {
    Write-Host "Variable does not exist"
}

In the above PowerShell script, the if statement checks if the variable is null or not. If the variable is null, it will print a message as “Variable does not exist”.

Conclusion

I hope the above article on how to check if PowerShell variables exist using the Test-Path and Get-Variable cmdlets is helpful to you.

You can create a robust and error-free script by checking for variable existence in PowerShell scripts. You can handle errors if a variable doesn’t exist to ensure script stability.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.