PoshCode Archive  Artifact Content

Artifact 779295f2b632c924d33f128db8c8bd02d94482bbd7b84dccab5a14484c926acb:

  • File count-object.ps1 — part of check-in [2df993104f] at 2018-06-10 13:12:04 on branch trunk — #a function to count how many items there are, whether its an array, a collection, a hashtable or actually just (user: karl prosser size: 1646)

# encoding: ascii
# api: powershell
# title: count-object
# description: #a function to count how many items there are, whether its an array, a collection, a hashtable or actually just
# version: 0.1
# type: function
# author: karl prosser
# license: CC0
# function: count-object
# x-poshcode-id: 2533
# x-archived: 2016-09-07T04:27:27
# x-published: 2011-03-01T14:19:00
#
# a single no array/non list/non collection object in which case it would be 1
#
#a function to count how many items there are, whether its an array, a collection, or actually just
# a single no array/non list/non collection object in which case it would be 1
function count-object ($InputObject)
{
 if ($inputobject -eq $Null ) { return 0}
 if ($inputobject -is [system.array]) { return $inputobject.length }
 if ($inputobject -is [system.collections.ICollection] -or 
     $inputobject -is [system.collections.IList] -or
     $inputobject -is [system.collections.IDictionary] )  { return $inputobject.count }
 #strings are ienumerable, they also have a length, but i think we want to treat 1 string as one object
 if ($inputobject -is [string]) { return 1 }
 #-1 to show that it is enumerable, but we can't know its length, it could be infinate, 
 #or take a long time even to enumerate without going over 
 if ($inputobject -is [system.collections.IEnumerable]) { return -1 }
 #otherwise just return 1
 return 1
}
set-alias count count-object
count (get-process)
count (1,2,3)
count "hello"
count 3
count @{first = 1; second = 2 }

$a = new-object system.collections.arraylist
[void] $a.add(4);
[void] $a.add("yo");

count $a