Search code examples
conditional-operatorpowershell-7.0

Ternary comparison outputs new value


PS C:\Users\Scott> $openlog = "YES"
PS C:\Users\Scott> ($openlog -eq "YES") ? ($openlog = "NO") : ($openlog = "YES")
NO
PS C:\Users\Scott> ($openlog -eq "YES") ? ($openlog = "NO") : ($openlog = "YES")
YES
PS C:\Users\Scott> ($openlog -eq "YES") ? ($openlog = "NO") : ($openlog = "YES")
NO
PS C:\Users\Scott> ($openlog -eq "YES") ? ($openlog = "NO") : ($openlog = "YES")
YES
PS C:\Users\Scott>

This works, ie it toggles the value, but it also writes it to the console. Why? How do I do this properly and not output the new value, without using | Out-Null?


Solution

  • You can use the below to set the variable without outputting to console.

    $openlog = $openlog -eq "YES" ? "NO" : "YES"

    I do not yet know why your example outputs to the console. I went through the implementation and this was a use case that was never handled and isn't handled during testing.

    Update: as mklement0 mentions below

    enclosing an assignment in (...) passes the value being assigned through