2

I have a powershell class that has method that can return an array of custom PSObjects, though I'm not sure how to define the method so that it won't complain. ie

class ThisIsAClass {
    MethodReturnsArray() {
        $thisArray = @()
        for ($i=0; $i -lt $total; $i++) {
            $item = New-Object -TypeName PSObject
            $item | Add-Member MemberType -NoteProperty -Name ID -Value i
            $item | Add-Member MemberType -NoteProperty -Name Text -Value "a"
        }
        return $thisArray
    }
}

1 Answer 1

4

You need to declare a return type for the MethodReturnsArray() method. You can assign the output from the for loop directly to $thisArray:

class ThisIsAClass {
    [array]MethodReturnsArray([int]$total) {
        $thisArray = for ($i=0; $i -lt $total; $i++) {
            $item = New-Object -TypeName PSObject
            $item | Add-Member -MemberType NoteProperty -Name ID -Value $i
            $item | Add-Member -MemberType NoteProperty -Name Text -Value "a"
            $item
        }
        return $thisArray
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ahhh, array was the keyword I was missing. I tried [@()]. I'll accept when the timer lets me :) Thanks!
Is [array] preferable/different in this case from [object[]]?
@TheMadTechnician Good question. From a performance perspective (I would assume), [object[]] or [psobject[]] is possibly slightly faster, but I find [array] easier to read

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.