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

Welcome Forums General PowerShell Q&A 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

 
Participant
2 years ago.

  • Author
    Posts
  • #58118

    Participant
    Points: 21
    Rank: Member
    #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.

  • #58120

    Participant
    Points: 15
    Rank: Member

    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.

The topic ‘If a user has no disabled PCs in AD, I get {} as result not 0. Why?’ is closed to new replies.