If a user has no disabled PCs in AD, I get {} as result not 0. Why?

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of JC Ruiz JC Ruiz 7 months, 1 week ago.

  • Author
  • #58118
    Profile photo of Hermann
    #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;
        $obj = New-Object -TypeName PSObject -Property $properties
        Write-Output $obj


  • #58120
    Profile photo of JC Ruiz
    JC Ruiz

    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.

You must be logged in to reply to this topic.