Blog

主に Steps Recorder を使ってKnowledgeを記録するブログです。間違いや分かりにく部分があったらコメントください。

SharePoint Online PowerShell 全アイテム削除

f:id:kllc:20180219170214p:plain

大量のアイテムをブラウザより手動で削除するのは大変ですよね。

今回は、リストのアイテムを一発で全件削除するCSOMサンプルプログラムを紹介します。

 

 

サンプルプログラムの紹介


# Read CSOM
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")

#サイトURL
$siteUrl ="サイトURLを入力"

#リスト名
$listName = "リスト名を入力"

#ユーザー
$username = "ユーザーを入力"
$password = Read-Host -Prompt "パスワード:" -AsSecureString

#インスタンス生成
$context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)

#認証情報
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$context.Credentials = $credentials


try
    {
        $counter=0
       
        $spQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
        $spQuery.ViewXml = "<View><Query></Query><ViewFields><FieldRef Name='Id' /></ViewFields><RowLimit>100</RowLimit></View>"

        $list = $Context.Web.Lists.GetByTitle($listName)

        do
        {
            $items = $list.GetItems($spQuery);
            $Context.Load($items)

            $Context.ExecuteQuery()

            $count = $items.Count
            Write-Host "残りアイテム" $count "件" -ForegroundColor Yellow

            while ($items.Count -gt 0)
            {
                $items[0].DeleteObject()
            }

            $spQuery.ListItemCollectionPosition = $items.ListItemCollectionPosition
        }
        while ($spQuery.ListItemCollectionPosition -ne $null)

        $Context.ExecuteQuery()
        Write-Host "アイテム削除完了" -ForegroundColor Yellow
    }
catch
    {
        Write-Host -ForegroundColor Red $_.Exception.ToString()
    }

 

 


今回のサンプルでは、100件ずつ取得してアイテム数が0件になるまで削除を繰り返しています。

 

 

なぜ、一括で削除を行わないのかというとSharePointにはリストビューの

アイテム数が5000件を超えると色々と制限されてしまいます。


※詳細は下記を参照ください。
https://blogs.technet.microsoft.com/sharepoint_support/2015/04/14/faq/
https://blogs.technet.microsoft.com/sharepoint_support/2015/05/15/31574/

 

 

リストビューのアイテム数が5000件以上の場合でも制限を回避する為に
アイテムのID列を100件ずつ取得してから削除するようにしています。

 

【コード抜粋】
$spQuery.ViewXml="<View><Query></Query><ViewFields><FieldRefName='Id' /></ViewFields><RowLimit>100</RowLimit></View>"

 


参考情報:CamlQuery.ViewXml プロパティ
https://msdn.microsoft.com/ja-jp/library/microsoft.sharepoint.client.camlquery.viewxml.aspx