LoginSignup
4
4

More than 5 years have passed since last update.

PowerShell CSOMを使ってSharePoint Onlineサイトコレクションにあるすべてのサブサイトを取得する

Last updated at Posted at 2019-02-10

SharePoint Server では AllWebs プロパティで取得できる

オンプレミスである SharePoint Server では、サーバーAPI の SPSite.AllWebs を使うことでサイトコレクションにあるすべてのサブサイトを取得できます。

このプロパティから返されるサブサイトにはトップレベルサイトも含みます。

SPSite members

Name    Description
AllWebs     Gets the collection of all Web sites that are contained within the site collection, including the top-level site and its subsites.

以下のように使います。

$site = Get-SPSite http://contoso.com
$allwebs = $site.AllWebs

SharePoint Online サイトコレクションには Allwebs がない

クライアントサイドAPIの Siteクラスにはすべてのサブサイトにあたるプロパティがありません。

Site members
すべてのサブサイトに該当するプロパティなし

SharePoint Online サイトは Web.Webs でサブサイトを取得する

サブサイトにあたる Webクラスには配下のサブサイトを取得するプロパティがあります。ただし、このプロパティが返すのは1階層下のサブサイトまでです。2階層以下のサブサイト(= 孫サブサイト)は含みません。

Web members

Name    Description
Webs Gets a Web site collection object that represents all Web sites immediately beneath the Web site, excluding children of those Web sites.

ファンクションを使ってすべてのサブサイトを取得する

Web.Websプロパティを再帰的に呼び出すことで起点とするサブサイト配下のすべてのサブサイトを取得できます。以下はそれをファンクションにしたものです。

#配下の全てのサブサイトを取得する
function GetSubWebs()
{ 
    Param
    ( 
        [Microsoft.SharePoint.Client.ClientContext]$context, 
        [Microsoft.SharePoint.Client.Web]$rootWeb 
    ) 

    $webs = $rootWeb.Webs 
    $context.Load($webs) 
    $context.ExecuteQuery() 

    $websList += $webs 

    foreach($sWeb in $Webs) 
    {   
        #自分(= このファンクション)を再帰的に呼び出して
        #孫サイトをすべて取得する
        GetSubWebs -RootWeb $sWeb -Context $Context 
    }

    return $websList
}

作成したファンクションは以下のように使用します。
$websCollection という配列を作成して、ファンクションの返り値(= サブサイト)を格納します。注意点として、起点になるサブサイトはファンクションの返り値に含まれないため、別個で配列に追加する必要があります。

#対象サイトのオブジェクトを取得する
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$ctx.Credentials = $credentials

$web = $ctx.web
$ctx.Load($web)
$ctx.ExecuteQuery()

#「配下の全てのサブサイトを取得する」ファンクションを呼び出す
$websCollection = @()
$websCollection += $web
$websCollection += GetSubWebs -rootWeb $web -context $ctx

SharePoint PnP を使う

SharePoint PnP Cmdlets を使うともっと簡単にすべてのサブサイトを取得できます。Get-PnPSubWeb にある Recurse パラメータを使うと孫サイトの取得までやってくれます。便利。

Connect-PnPOnline -Url $siteUrl -Credentials $credentials

$webs = @()
$webs += Get-PnPWeb
$webs += Get-PnPSubWebs -Recurse
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4