Link to home
Start Free TrialLog in
Avatar of NJThomson
NJThomson

asked on

How to stop PowerShell function changing return type of ArrayList or string[]

I'm attempting to return either a .NET ArrayList collection or a string array
(string[]) from a PowerShell function. PowerShells runtime "unravelling" is not
behaving as described, and the various work arounds I've read about don't address
the issue.

What is being returned is also not what I expect or have read about.

The following code returns a System.Array with a count of 6 and the values
0 1 2 A B C. What I want is only 3 values A B C.

function GetArrayOfStrings([string[]] $strings)
{
      # set up a collection to "read them in"
      $stringAryList = New-Object "System.Collections.ArrayList"
      foreach($string in $strings)
      {
            $stringAryList.Add($string)
      }

            $stringAry = $stringAryList.ToArray()
            return $stringAry
}

#main

$stringAry = GetArrayOfStrings(("A", "B", "C"))

foreach($str in $stringAry)
{
      Write-Host $str
}

The returned  values suggest PowerShell is flattening a hash table where 0 1 2 are the index values and A B C the content values.

Attempting to "wrapper" the return using "," or @(,) syntax doesn't improve things much.

      return ,$stringAry
      return @(,$stringAry)
      
Both result in a System.Array containing {0, 1, 2, System.Array} and an output of

0
1
2
A B C

This is better, but the only way to get the string[] as a System.Array is to do the
following:

$actualStringArray = $stringAry[$stringAry.Count-1]

Some of my readings online have suggested the array is unravelled to make it simpler
for human readability or to be used in foreach, but I certainly don't see how...

I have identical problems when attempting to return the ArrayList

Looking for a way to fully defeat the unravelling or a way to use the results in a foreach,
but only for the content values, not the index values.
ASKER CERTIFIED SOLUTION
Avatar of NJThomson
NJThomson

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of NJThomson
NJThomson

ASKER

Found a good answer in an online book in Safari....