Count length of array and return 1 if it only contains one element

$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?

4 Answers

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") 
3

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

1

declare you array as:

$car = array("bmw") 

EDIT

now with powershell syntax:)

$car = [array]"bmw" 
1

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.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like