PowerTip: Find Number Elements in a PowerShell Array

PowerTip: Find Number Elements in a PowerShell Array

  • Comments 3
  • Likes

Summary: Easily find the number of elements in a Windows PowerShell array.

Hey, Scripting Guy! Question How can I find how many elements are in a Windows PowerShell array?

Hey, Scripting Guy! Answer You can find the number of elements in a Windows PowerShell array in the following ways:

[array]$a = 1,2,3,4,5

$a.Count

$a.Length

$a.GetUpperBound(0)

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • This is flawed. If there is only one element in an Array, it returns the length of the string, instead of returning 1.

  • After digging in a little more (I am not a Powershell Guy) I realized that problem is a result of Powershell's dynamic typing behavior. Using a Strongly Types Array fixed the issue. I was creating an array like $a = ls *.bak|foreach {$_.name} but I should have done @($a = ls *.bak|foreach {$_.name})

  • I meant $a = @($a = ls *.bak|foreach {$_.name}) Phew.