Search code examples
powershellnullactive-directory

Comparison and logical operations with $null and brackets


Today I approached a curious thing on my console. For example, I have:

$test = "test" 
$null -eq $test

This returns False, obviously. But if instead we go by:

-not {$null -eq $test}

This returns False too!

I thought the curled brackets {} -blocks of code, as I recall- interacted as the normal ones (). But I don't get why I get this kind of returns. How powershell works around comparison and logical operations with code inside of curled brackets?


Solution

  • In PowerShell, the use of curly braces "{}" can serve different purposes, and they are not interchangeable with parentheses "()".
    Curly braces are commonly used for script blocks and script block expressions, which have specific behaviours when used in comparison and logical operations.

    -not {$null -eq $test}
    You are creating a script block and then negating it with -not. The result of a script block is not evaluated as a Boolean value directly, which is why you are getting False.

    -not ($null -eq $test)
    This will correctly negate the result of the comparison, and you will get True.
    So, to achieve the expected behaviour in your logical operation, use parentheses () to group the expression you want to negate. This will return True because you are negating the result of the comparison.