33
$cars = "bmw","audi","volvo","vw"
echo $cars.length

returns 4, but

$cars = "bmw"

returns 3 because it counts the characters..

Is there a way I can return 1 if the array only contains one item?

Sune
  • 3,080
  • 16
  • 53
  • 64

4 Answers4

40

A couple other options:

  1. Use the comma operator to create an array:

    $cars = ,"bmw"
    $cars.GetType().FullName
    # Outputs: System.Object[]
    
  2. Use array subexpression syntax:

    $cars = @("bmw")
    $cars.GetType().FullName
    # Outputs: System.Object[]
    

If you don't want an object array you can downcast to the type you want e.g. a string array.

 [string[]] $cars = ,"bmw"
 [string[]] $cars = @("bmw")
Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
  • Thank Andy! I see that my script is failing because the value if system.object[]. Is there a way to process the contents as strings? – Sune Mar 06 '12 at 10:08
  • 1
    @Sune Yea you just down-cast to a string array. I added examples. – Andy Arismendi Mar 06 '12 at 10:25
  • The proposal to use string array didn't work for me. I'm grabbing data from SQL database and it returned "System.Data.DataRow" instead of values. So I had to use the solution with @($array).count below. – Hardoman Apr 13 '17 at 13:50
24

Instead of writing echo $cars.length write echo @($cars).length

jon Z
  • 15,838
  • 1
  • 33
  • 35
  • 1
    That helped me a lot. An array with 1 element "$packs.Count" didn't returning anything. With several elements it worked well. After changing it to "@($packs).count" it returned 1 for 1 element too. Great thanks! Can you explain this behavior? – Hardoman Apr 13 '17 at 13:46
7

declare you array as:

$car = array("bmw")

EDIT

now with powershell syntax:)

$car = [array]"bmw"
Vikram
  • 8,235
  • 33
  • 47
  • Thank you for your help! I did not accept it as an answer though, because the syntax is off. Maybe for another language? Thank you anyways:) – Sune Mar 06 '12 at 08:46
2

Maybe I am missing something (lots of many-upvotes-members answers here that seem to be looking at this different to I, which would seem implausible that I am correct), but length is not the correct terminology for counting something. Length is usually used to obtain what you are getting, and not what you are wanting.

$cars.count should give you what you seem to be looking for.

user66001
  • 774
  • 1
  • 13
  • 36
  • Depends on the objects-type with these properties. Say a `file` (or `string`), its `length` refers to its size, whereas its `count` refers to the number of files in question. So they are not identical. But with an `array`, the `length` of an `array` and its `count` are identical. If so inclined, jump into the rabbit hole @ [Length, Count and arrays – Cloud Notes](https://www.cloudnotes.io/length-count-and-arrays/). It is not that deep :) – pavol.kutaj Mar 23 '21 at 12:00