Google

2014-12-11

Even False counts in PowerShell

I was testing one of my PowerShell scripts and noticed a problem, a PowerShell gotcha if you will, that's actually quite easy to miss.

I had something like this in the script:

$rebootGroups=@(([adsisearcher]"(&(objectCategory=computer)(cn=$env:COMPUTERNAME))").FindOne().Properties.memberof -replace '^CN=([^,]+).+$','$1' -match 'grp.reboot.')


That is a one liner to check if the current computer where the script is running is member of any AD groups that starts with 'grp.reboot'.

Later in the script, I had an if statement checking if I got any groups back and act on them:

If ($rebootGroups.count -ne 0) {...}


If computer is indeed in any one of these groups, we would get a count greater than zero.
What happens if computer is not member of any such groups? We might expect to get back a count of '0', but in fact we get a count of '1'.

Here is proof:

PS C:\> $a=@($false)

PS C:\> $b=$false

PS C:\> $c=$true

PS C:\> $a.count;$b.count;$c.count

1

1

1



It could be argued that the first one makes some sense. At the end, it is an [array] type with a single element and hence count should not be 0.

The more interesting is the second one '$b', which is a boolean and regardless of its value ($true or $false), the count property of a boolean is 1.

So, in this case, we would fix the logic by checking if $false was returned, as ($rebootGroups.count -ne 0) will never be equal to 0!