powershell testing a variable that hasnt being assign yet powershell testing a variable that hasnt being assign yet powershell powershell

powershell testing a variable that hasnt being assign yet


Any unassigned variable will have a value of null, not a data type of null. So, just do this:

If ($ProgramName -ne $null)

...that will return TRUE if it's been assigned to a non-null value.

An even easier check to make is

IF($ProgramName)

Which will check if that is $null or not, though the logic is reversed, so you could use

IF(!$ProgramName)

Edit:

Ruffin raises a good point about strictmode in comments. This method will work as well:

Test-Path variable:ProgramName or Test-Path variable:global:ProgramName if it's explicitly global scoped, for instance. This will return $true or $false depending on if the variable exists.


Test-Path variable:\var should do what you want, I guess.


Contrary to answers above

Test-Path variable:ProgramName  

Might not be what you are looking for because it only tests for the existence of the variable. If the Variable is set to $null it will still return $true.

Therefore in strictmode you may have to test for it's existence existence and whether it is non-empty.

Set-StrictMode -version Latest#TODO Add a scope parameterFunction IsEmpty([string]$varname){   if (Test-path "variable:$varname"){       $val=(gi "variable:$varname").value      if ($val -is [bool]) {$false}      else {$val -eq '' -or $val -eq $null} }   else{ $true }}#TEST:if (test-path variable:foobar){remove-variable foobar} ; IsEmpty foobar$foobar=$null; IsEmpty foobar$foobar='';  IsEmpty foobar;$foobar=$false;  IsEmpty foobar#Results:TrueTrueTrueFalse

Strict mode kind of takes some of the fun out of scripting...