2

#Inside the function the arrayList has 51 items, but the function returns a 102 items arrayList #0 to #51 are int values 0 to 51, #51 to #101 are the expected json objects?

function Get-RedditTopics () {
    
    $arrayList = New-Object -TypeName "System.Collections.ArrayList"
    $url = 'https://www.reddit.com/r/worldnews/.json'
    $pages = 2
    
    $after = ""
    for ($i = 0; $i -lt $pages; $i++) {
    
        if ($i -gt 0) {
            $url = $url + "?after=$after"
        }
    
        $result = Invoke-RestMethod $url
    
        foreach ($item in $result.data.children) {
            $arrayList.Add($item.data)
        }
    
        $after = $result.data.after
    }
    return $arrayList #51 items, ok!
}

$redditTopics = Get-RedditTopics #function returns $arrayList with 102 items
write-host "redditTopics count: $($redditTopics.Count)"
3
  • 4
    yes, 51 + 51 = 102 (because each time you add to an arraylist, it outputs the index). $null = $arrayList.Add($item.data) should do it :) Commented Apr 18, 2022 at 21:39
  • 4
    In your case it is ArrayList.Add() that returns the index of the added array element. This is added as implicit output of your function. See the accepted answer of the linked duplicate for details about how implicit output works and what you can do to suppress it. Commented Apr 18, 2022 at 21:40
  • 2
    @Santiago Squarzon, thank you! Commented Apr 18, 2022 at 21:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.