Author Posts

November 18, 2016 at 9:35 am

#This script counts pcs per user. Enabled and disabled.
#If a user has no disabled PCs in AD, I get {} as result not 0. Why?

$samaccountnames = "abc","def","ghi"
foreach ($samaccountname in $samaccountnames)
{
    $comps = Get-ADComputer -Filter * | Where-Object { $_.distinguishedname -like "*$samaccountname*"}
    $count = $comps.count
    $count_enabled  = ($comps | Where-Object {$_.enabled -eq $true }).count
    $count_disabled = ($comps | Where-Object {$_.enabled -eq $false}).count
    
    $properties = [ordered]@{'user'=$samaccountname;
                    'PCs'=$count;
                    'PCs_enabled'=$count_enabled;
                    'PCs_disabled'=$count_disabled;
                    }
    $obj = New-Object -TypeName PSObject -Property $properties
    Write-Output $obj
}

Thanks.

November 18, 2016 at 10:10 am

Because the .Count property only exists on an ARRAY and the result of $Comps | Where-Object
can sometimes be an array (when 2 or more objects), $null (empty collection), or the computer object itself (which fortunately has not a .Count property).

Suggestion : Use ALWAYS Set-StrictMode -version Latest at the beginning of all your scripts, you'll see the error.

One Possible Solution : Use a CAST to an array (the @ operator) as in

$count_enabled  = @($comps | Where-Object {$_.enabled -eq $true }).count

Others : Use Measure-Object instead of .Count, or predefine the type of the variable as a System.Object[].

Note : PS3 does this cast automatically, but only for some object types, and only for the .Count property.
Risky... and showing you don't really understand PowerShell pipeline model.