powershell recursive function array values disappears

This topic contains 1 reply, has 1 voice, and was last updated by  malik 5 months ago.

  • Author
    Posts
  • #70963

    malik
    Participant

    Before calling recursive function – RecursiveWebs, $webinfo.count is 1. During the execution of recursive function, count is increased but as soon is recursive function is completed and control return to main function, $webinfo.count again decreases to 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
        }
    }
    
  • #71063

    malik
    Participant

    Replaces $webinfo with $Global:webinfo everywhere in the code and it did the trick

You must be logged in to reply to this topic.