Array appears to be empty after passing to a function?

Tagged: 

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Rob Simmers Rob Simmers 1 year, 7 months ago.

  • Author
    Posts
  • #25898
    Profile photo of dean warren
    dean warren
    Participant

    Array appears to be empty after passing to a function? That is the array has the correct number of elements, but not the content.

    e.g.

    function createArray ( [int]$length )
    {
        $array = @("") * $length
        return $array
    }
    function doSomethingWithArray( [string[]]$myArray )
    {
        $i = 0
        foreach ($e in $myArray)
        {
            write-host $i.tostring()
            write-host $e.tostring()
            $i++
        }
    }
    $myArray = createArray 3
    doSomethingWithArray $myArray

    Output is somehting like
    0

    1

    2

    Note the gaps? Note I have to do write-host $e.tostring() as the element is not a string?

    Is the array wrapped as an object? are the elements wrapped as an object? Is this a scope issue?

    Please help ASAP.

    Thanks

  • #25906
    Profile photo of Tim Pringle
    Tim Pringle
    Participant

    Hi Dean

    ASAP is what you pay contractors for.... 😉

    I think you're possibly getting confused between creating the array and actually populating it. The gaps are occurring because you're trying to write to the screen empty elements in the array. You only define a static array of three elements, you are not populating it.

    You're seeing the space because it's writing out the blank value of the array with a line feed at the end. This is standard behaviour.

    Not certain what you mean about the .tostring, my code below works in the same way as yours without the .tostring.

    function createArray ( [int]$length )
    {
        $array = @("") * $length
        return $array
    }
    function doSomethingWithArray( [string[]]$myArray ) {
        $i = 0
        foreach ($e in $myArray)
        {
            write-host $i
            write-host $e
            $i++
        }
    }
    $myArray = createArray 3
    doSomethingWithArray $myArray
    
  • #25916
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    A side note, you don't need to pre-create arrays and then fill them such as in VBScript DIM and REDIM. Arrays are really simple and Powershell will convert any of this to an array:

    #Powershell will automatically create this as an array
    $array1 = "Computer1", "Computer2", "Computer3"
    #Casting option to force into and array
    [array]$array2 = 1, 2, 3
    #Another casting option using a @()
    $array3 = @("Dog", "Cat", "Fish")
    
    #Add a value to an array
    $array1 += "Computer4"
    
    #Array using a range
    $array4 = 1..5
    
    #An array of arrays
    $array1, $array2, $array3, $array4 | foreach{
        $_.GetType()
    }
    

You must be logged in to reply to this topic.