PowerShell – Get Number of objects in List

Background

Had a need to get the number of objects in a list and as usual could not figure out a reliable way, unlike I  cheated and looked online.

 

Sample Code

Please keep in line that this is just a code snippet and will not work if ran as is.

 


$iLinkID = 0
$iNumberofLinks = 10
$objLinks = @()

# Iterated through links
while ($iLinkID -lt $iNumberofLinks)
{

	# Get Link Node
	$objLinkNodeX = $objLinksAll[$iLinkID]

	# Get Link HREF
	$linkHREF = $objLinkNodeX.href

	# Get Link Text
	$linkText = $objLinkNodeX.innerText

	# If matches what we are looking for
	if (
			  ($linkHREF -like $searchTagWildcard) `
		  -or ($linkText -like $searchTagWildcard) `
	   )

	{

		#Increment Number of matches
		$iNumberofMatches = $iNumberofMatches + 1;

		# create match object
		$objPSLinkNode = New-Object PSObject

		# set match object properties
		Add-Member -InputObject $objPSLinkNode -MemberType NoteProperty -Name innerText -Value ""
		Add-Member -InputObject $objPSLinkNode -MemberType NoteProperty -Name href -Value ""

		# set match object property data
		$objPSLinkNode.href = $objLinkNodeX.href
		$objPSLinkNode.innerText = $objLinkNodeX.innerText

		# Add matching node to list of Nodes
		$objLinks += $objPSLinkNode

	}

	#move to next link
	$iLinkID = $iLinkID +1

} #while ($iLinkID -lt $iNumberofLinks)

# Wrong way of counting Number of objects in list [1]
$iNumberofObjectsInListWrong = $objLinks.Count
$strLog = "Number of entries in array {0}" -f $iNumberofObjectsInListWrong
Write-Host -Message $strLog

# Wrong way of counting Number of objects in list [2]
$iLenghtofObject = $outarray.Length
$strLog = "Array Length {0}" -f $iLenghtofObject

# Wrong way of counting Number of objects in list [3]
$iObjectUpperBound = $outarray.GetUpperBound(0)
$strLog = "Array UpperBound {0}" -f $iObjectUpperBound

#Proper way
$iNumberofObjectsInListProper = $objLinks | measure-object | select count
$strLog = "Number of entries in array {0}" -f $iNumberofObjectsInListProper
Write-Host -Message $strLog

Summary

I wish I know why the other tries do not work, but I am grateful to the Net.

The blessing of the LORD brings wealth, without painful toil for it

 

 

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s