I ran across this line the other day that a student wrote in a beginning PowerShell class. I can’t figure out how it works since there is no size property for the Win32_QuickFixEngineering object type (which is the object type passed by the Get-Hotfix cmdlet). What is size referring to that makes this command work?
this is because of the type casting and comparison. IMO it compares the length if the $_.size (which is a known existing property hence length is 0) to the ‘5MB’ which has length greater than empty.
the output will be different if you use -gt instead of -lt.
Thank you. Excellent answers. Indeed it does give different results with -gt. And I was unaware of the “null” response for unknown property values. This has been very excellent help and cleared a lot of things up.
this is working because, if some property is not present for an object Powershell will create a new custom property. have a look at the below code.
PS C:\windows\system32> get-hotfix | select size
size
It won’t give any error instead it will create a new property called size. As size does not have any value it will hold $null.Now if you compare by using (-lt) it will always return true as ($null -lt any value) is true. Have a look at the below code,
PS C:\windows\system32> get-hotfix | for each {$_.size -lt 5}
True
True
True
True
True
True
True
True
True
now if you change the compare operator to (-gt )it will always give false. As $null -gt any value is false.
Well, $null is $null… it has no type. It is not equal to 0 by itself.
But sometimes, variables in PowerShell can be converted (Cast) to another type. $Null can be converted to [int], and it has to have a valid value. Both
yes it is a special case, just had a chat with Bruce Payette and PFB his comments.
Bruce Payette:
$null in a numeric context (like comparing to a number) is converted to 0. And since 0 is less than 1,
$null is special-cased by the runtime. It doesn't actually get converted, but is treated as a value less than 0 but greater that the smallest negative number. Likewise in a string context, it is treated as being 'smaller' than the smallest possible string i.e. ''.