PowerTip: Find Number Elements in a PowerShell Array

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




Comments (4)

  1. Gregg Leventhal says:

    This is flawed. If there is only one element in an Array, it returns the length of the string, instead of returning 1.

  2. Gregg Leventhal says:

    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})

  3. Gregg Leventhal says:

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

  4. Pete Taylor says:

    Thank you so much Gregg Leventhal! I was scratching my head over why one of my (large) Powershell scripts would only work when a particular array held more than 1 element…