PowerShell v3 0 1 eq true

Okay, its an odd title, I admit it. But, it cuts straight to the chase about one of the subtler points of PowerShell syntax. In Win32 API programming, result codes are often returned as numeric values. So, FALSE and 0 are the same (in most cases) and TRUE often connects with positive integers. This proved to hold true while working on a recent Win32/P/Invoke function for SystemParaemterInfo. As noted in the MSDN documentation,
SystemParametersInfo
regarding return values,
Nonzero indicates success. Zero indicates failure. This function will return ERROR_RESOURCE_DISABLED if you attempt to set the values SPI_SETBATTERYIDLETIMEOUT, SPI_SETEXTERNALIDLETIMEOUT, or SPI_SETWAKEUPIDLETIMEOUT when GWES suspend management is disabled.
So, when I run my command,
 [Win32Utils.User32]::SystemParametersInfo(1,2,[Intptr]::Zero,1)
and it returns $false, I could easily be mislead by these results. None of the parameters indicated the returned result would be a bool. However, knowing that integers and boolean values can masquerade as each other, I can see the result more meaningfully as $false = 0, or, in this case, a failed call to the method.

For reference, here are some patterns to keep in mind:

  • $false  ? 0
  • $true  ? ¬0
This can be proven with the following commands:
  • -1 -eq $false - $false
  • 1 -eq $false - $false
  • 0.5 -eq $false -$false
  • 0 -eq $false - $true
  • -1 -eq $true - $true
  • 1 -eq $true - $true
  • 0.5 -eq $true -$true
  • 0 -eq $true - $false
The moral here: if you are working with older Windows code be sure you are familiar with the result codes AND be sure you know what true and false are in the interpreted language.

Related Posts by Categories

0 comments:

Post a Comment