2
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?

2 Answers2

2

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

Otter
  • 1,086
  • 7
  • 18
2

Otter's helpful answer offers the optimal solution for your use case, which bypasses the problem with your code:

As for:

it also writes it to the console. Why?

PowerShell allows you to use assignments as expressions, by enclosing them in (...), the grouping operator:

That is, something like ($var = 'foo') also outputs the value being assigned, in addition to assigning to variable $var:

PS> ($var = 'foo')
foo

That is, the value is output to PowerShell's success output stream (see the conceptual about_Redirection help topic), which by default goes to the host (console).

mklement0
  • 382,024
  • 64
  • 607
  • 775