首页 文章

函数未返回预期对象

提问于
浏览
8

这个PowerShell函数我有一个奇怪的情况 . 假设返回ArrayList对象,但是当循环仅向ArrayList添加1项时,该函数返回SPList项而不是Expected ArrayList对象 . 我很难理解为什么PowerShell会以这种方式运行 .

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;

}

这是调用代码:

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

3 回答

  • 1

    那里有一个隐含的管道,管道不会将数组,集合和arraylists“展开”一级 .

    试试这个:

    return ,$CORules
    
  • 0

    或者您可以将变量$ CORulesResult强制转换为前面带有 [Array] 的数组

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

    当我使用[System.Collections.ArrayList]而不是普通的固定大小数组时,我也有类似的问题 . 返回的对象不是我希望的数组元素,而是整个数组,除了我想要返回的一个元素之外它是荒芜的 . 谈论弄乱堆栈 .

    解决方案很简单:使用[System.Collections.ArrayList]停止

    这是你如何声明和处理$ CORules .

    $CORules = @()
    
    ...
    
    $CORules = $CORules + $list
    

    Viva le Bash

相关问题