Search code examples
variablespowershellif-statementconditional-statements

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 
    }
}

Solution

  • 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.