Loading...
 

Greg`s Tech blog

Counting a collection in Powershell

Wednesday 04 of July, 2012
I'm writing a script for AD that will manage for old computer accounts and disable or delete them per our policy. I ran into an interesting issue that I want to document so I remember it.

The query I ran to find old accounts sometimes return 0 objects, sometimes 1, and most times > 1. While testing the code, I noticed that It was having an issue when the return set was zero so I added this code to test for that case:

$oldComps = get-adcomputer -filter ...
if ($oldComps -eq $null) {
        $count = 0 } else {
        $count = ($oldComps).count
        }
    write-host "Processing $count accounts over $daysToDisable for disable"

When this runs I get a nice message saying how many accounts will get processed - unless there is one item returned by the query - in which case $count is blank. Hmmmm.

I went nuts over this for 15 minutes then thought to ask the internet using this query:
"powershell AD collection count one item"

I found an article that suggested the issue was that when one item is returned from the PowerShell command, it is returned as a scalar (single object as everything in Powershell is an object) and not as a collection. The simple fix for this is to wrap the command to force it to return an array
@( ... )

So my code from earlier becomes:
$oldComps = @(get-adcomputer -filter ...<snip>)
if ($oldComps -eq $null) {
        $count = 0 } else {
        $count = ($oldComps).count
        }
    write-host "Processing $count accounts over $daysToDisable for disable"

We can credit this as today's thing learned.