1

Good day to all! I have some function which splits an input array to $partitionCount partitions. Return value should be an array of arrays. If $partitionCount equals to 1 you dont need to perform some split logic and you can return input array itself. In that case powershell flattens return result into simple array (not array of arrays as required).

I have tried following approaches found with Stackoverflow and other resources:

  1. return @($input) flattens result into single array
  2. return @(,$input) also flattens result into single array
  3. return @($input, @()) it works but uses empty array to prevent flattening, bad one
  4. $bucket = @(Split-Array $input 1) place an array directive in call site, works fine, but you should place it in each call, which is very confusing and not obvious

Is there any right way to handle that case?

0

1 Answer 1

1

To prevent flattening of a single-item array, prepend a comma to the array you're trying to return (,@($value)):

function Get-SingleArray {
    param($InputArray)

    return ,@($InputArray[0])
}

Demonstration:

PS C:\> $a = Get-SingleArray 2,3,4,5
PS C:\> $a[0] -eq 2
True
PS C:\> $a.GetType.FullName
System.Object[]
Sign up to request clarification or add additional context in comments.

1 Comment

It seems that it does not working: function Return-Array([array]$data) { return ,@($data) } $a = Return-Array @(1,2,3) $a.Length #3

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.