Tuesday, 23 February 2016

Get all site collections in SharePoint Online using PowerShell

In previous post, I have written C# code sample to get the list of all site collections in SharePoint Online using SharePoint's client object model (CSOM). In this article, I am going to write PowerShell script sample to retrieve all site collections in a SharePoint tenant.

Before proceed, you need to download and install the SharePoint Server 2013 Client Components SDK

The below powershell script get all sites collection from the given SharePoint tenant. You have to provide your own tenant url, admin username and password.

# Initialize client context
$adminURL = 'https://MyTenant-admin.sharepoint.com/'
$username = 'admin@MyTenant.onmicrosoft.com'
$password = 'MyPassword'
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($adminURL)
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username,$securePassword)
$clientContext.Credentials = $credentials

# Enumerate all site collections

$tenant = New-Object Microsoft.Online.SharePoint.TenantAdministration.Tenant($clientContext)
$props = $tenant.GetSiteProperties(0, $true)
foreach($sp in $props)
       Write-Host 'Title:' $sp.Title
       Write-Host 'Url:' $sp.Url
       Write-Host '-----------------'


1 comment:

  1. Why not use the cmdlets instead? Way less code..

    $cred = Get-Credentials
    Connect-SPOService -url https://contoso-admin.sharepoint.com -Credential $credential
    Get-SPOSite | Select Title, Url

    (don't forget the '-admin' in the url!)