Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell testing a variable that hasnt being assign yet

I want to test to see if a variable has been assigned a variable and if not perform action. How can this be achieve?

I've attempted it with the following code but receive the error: The right operand of '-is' must be a type.

$ProgramName is not assigned at this point.

If ($ProgramName -isnot $null) {
    $ProgramName = $ProgramName + ', ' + $cncPrograms
}
Else {
    If ($cncPrograms -isnot $null) {
    $ProgramName = $cncPrograms 
    }
}
like image 300
resolver101 Avatar asked Sep 02 '25 15:09

resolver101


2 Answers

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.

like image 163
JNK Avatar answered Sep 05 '25 09:09

JNK


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

like image 20
David Brabant Avatar answered Sep 05 '25 09:09

David Brabant