递归函数 - 数组值消失

时间:2017-05-18 00:52:22

标签: arrays powershell recursion

在调用递归函数(RecursiveWebs())之前$webinfo.Count是1.在执行递归函数期间,Count会增加,但是一旦递归函数完成并且控制返回对于主函数,$webinfo.Count再次减少到1。

function RecursiveWebs($web) {
    $Properties = @{
        Title = $web.Title
        URL = $web.Url
    }

    $webinfo += New-Object PSObject -Property $properties       
    foreach ($w in $web.Webs) {
        if ($w.Webs.Count -gt 0) {
            RecursiveWebs $w
        }
    }
}

$global:webinfo = @() 
$sites = Get-SPOSite -Limit All
foreach ($site in $sites) {
    Write-Host $site.Url
    try {
        $Properties = @{
            Title = $site.Title
            URL = $site.Url            
            NoOfSubsites = $site.Webs.Count        
        }    

        $webinfo += New-Object PSObject -Property $properties

        if ($site.Webs.Count -gt 0) {
            RecursiveWebs $site
        }        
    } catch  {
        Write-Host $_ -ForegroundColor Red
    }
}

1 个答案:

答案 0 :(得分:0)

将$ webinfo替换为$ Global:webinfo代码中的所有地方,并且它实现了技巧