Figuring Out If That Powershell Variable Exists

Richie Lee has a method for checking whether a variable exists in Powershell:

Recently I needed to check that a variable exists in the PowerShell session currently running. This is actually far easier than it sounds. So here is a simple demo for how it works. The magic here is the “Test-Path variable:my_variable” on lines 4. It tests that a variable of that name exists. If it does, great, let’s print out the value. If not, let’s alert that it doesn’t. The second example of this on line 11 will do exactly that.

Read on to see Test-Path in action.

Related Posts

Powershell: Text Search In A Table Value

Shane O’Neill clarifies a misunderstanding in Powershell: and you are running the following PowerShell command to check if the results contain a value… 1 2 3 $String = "abc" $Array = @(Invoke-Sqlcmd -ServerInstance "SQLServer" -Database "Database" -Query "SELECT code FROM dbo.users") $Array.Contains($string) It will return FALSE. Now we know that the FALSE is false because we know that the string […]

Read More

Basic Powershell Regex

Adam Bertram shows how to use regular expressions for pattern matching in Powershell: However, regex has traditionally been a topic that most IT pros shy away from when they first see how it works. Admittedly, regex does take a bit of getting used to, and you’re still probably going to have to do some Googling […]

Read More