ChiliYago
ChiliYago

Reputation: 12289

Function not returning expected object

I have a strange situation with this PowerShell function. It is suppose to return the ArrayList object but in the case when the loop only adds 1 item to the ArrayList the function returns the SPList item instead of the Expected ArrayList object. I am stumped on why PowerShell is behaving this way.

function Get-ContentOrganizerRules
(
    [System.String]$siteUrl = "http://some.sharepoint.url"

)
{
    Write-Host -ForegroundColor Gray "Searching for Content Organizer Rules: "  $siteUrl


    # ArrayList to hold any found DataConn Libs
    [System.Collections.ArrayList]$CORules = New-Object System.Collections.ArrayList($null)


    $lists = Get-SPWeb $siteUrl |
        Select -ExpandProperty Lists |
        Where { $_.GetType().Name -eq "SPList" -and  $_.hidden }

    foreach($list in $lists)
    {
        #Write-Host $list ;

        foreach($contenType in $list.ContentTypes){
            if($contenType -ne $null){
                if($contenType.Id.ToString() -eq "0x0100DC2417D125A4489CA59DCC70E3F152B2000C65439F6CABB14AB9C55083A32BCE9C" -and $contenType.Name -eq "Rule")
                {
                    $CORules.Add($list)>$null;
                    Write-Host -BackgroundColor Green -ForegroundColor White "Content Organizer Rule found: " $list.Url>$null;
                }
            }
        }
    }

    return $CORules;

}

This is the calling code:

$CORulesResults = Get-ContentOrganizerRules $web.URL;
                    if($CORulesResults.Count -gt 0){
                        $Results.AddRange($CORulesResults);
                    }

Upvotes: 8

Views: 5637

Answers (3)

mjolinor
mjolinor

Reputation: 68273

There's a implicit pipeline there, and pipelines tend to "unroll" arrays, collections and arraylists one level.

Try this:

return ,$CORules

Upvotes: 9

phazenator
phazenator

Reputation: 1

I had a similar problem as well, when I used [System.Collections.ArrayList] instead of normal fixed size arrays. The object being returned wasn't the array element I hoped for, but the entire array, and it was barren except for the one element I wanted to return. Talk about messing up the stack.

The solution was simple: Stopped using [System.Collections.ArrayList]

Here's how you would declare and handle $CORules.

$CORules = @()

...

$CORules = $CORules + $list

Viva le Bash!

Upvotes: 0

Solaflex
Solaflex

Reputation: 1432

Or you can force the variable $CORulesResult to an Array with [Array] in front

[Array]$CORulesResults = Get-ContentOrganizerRules $web.URL;
                        if($CORulesResults.Count -gt 0){
                            $Results.AddRange($CORulesResults);
                        }

Upvotes: 2

Related Questions