Tuesday, June 2, 2015

Get all sites in a SharePoint Site Collection using the PowerShell and CSOM

$host.Runspace.ThreadOptions = "ReuseThread"

#Function definition
function Get-AllSites($siteUrl, $userName, $password, $domain)
        #Save result in temp variable
        $results = @()

        #Create client context
        $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) 
        $credentials = New-Object System.Net.NetworkCredential($userName,$password,$domain)  
        $ctx.Credentials = $credentials 

        #Get site
        $rootSite = $ctx.Web
        #Loading root site     
        foreach($site in $rootSite.Webs){
            #Load sites under each subsite

            Write-Host $site.Url -ForegroundColor Green
            #Create object for CSV row           
            $details = new-object PSObject
            $details | add-member -membertype NoteProperty -name "Site URL" -Value $site.Url
            $results += $details

            #Go for subsites if it has child sites
            if($site.Webs.Count -gt 0) {

                $results += Get-AllSites $site.Url $userName $password $domain
    catch [System.Exception]
        write-host -f red $_.Exception.ToString()   
    return $results

$siteUrl = "http://contoso/sites/hr"
$userName = "username"
$password ="password"

#Add Client Object Model Assemblies        
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Call fuction
$path = Get-Location
Get-AllSites $siteUrl $userName $password $domain | export-csv -Path $path\List.csv -NoTypeInformation

Write-Host "Report exported to CSV, please check file on location: $path"