Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delete all list Item versions from site and sub sites using CSOM and PowerShell
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
Set-Location $PSScriptRoot
$pLoadCSOMProperties=(get-location).ToString()+"\Load-CSOMProperties.ps1"
. $pLoadCSOMProperties
Function DeleteVersionsFromLists($web, $versionCount)
{
#Get all lists in web
$ll=$web.Lists
$context.Load($ll)
$context.ExecuteQuery();
foreach($list in $ll)
{
if($list.EnableVersioning)
{
$rootFolder = $list.RootFolder
#Get items from list
$qry = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
$items = $list.GetItems($qry)
$context.Load($items)
$context.Load($rootFolder);
$context.ExecuteQuery();
foreach($item in $items)
{
if($list.BaseType -eq "DocumentLibrary"){
$file = $item.File;
$context.Load($file);
$context.ExecuteQuery();
Load-CSOMProperties -object $file -propertyNames @("ServerRelativeUrl");
$context.ExecuteQuery() ;
$itemUrl = $file.ServerRelativeUrl
}
else
{
$itemUrl = $list.RootFolder.ServerRelativeUrl + "/" + $item.Id + "_.000";
}
# "/sites/prasad/teamsite/Lists/MyList/30_.000”
if($itemUrl -ne $null)
{
$versions = $context.Web.GetFileByServerRelativeUrl($itemUrl).Versions;
$context.Load($versions)
$context.ExecuteQuery()
$versionCount = $versions.Count
#adjust counter 0 to more if certain number of versions needs to be retained.
if($versionCount -gt 0)
{
for($i=0;$i -lt $versionCount ; $i++)
{
$versions[0].DeleteObject()
$context.ExecuteQuery()
}
}
}
}
}
}
}
$password = Read-Host -Prompt "Enter password" -AsSecureString
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials("reshmee@reshmee.onmicrosoft.com", $password)
#$siteUrl = "https://yourtenant.sharepoint.com/sites/yoursitecollection"
$siteUrl = "https://reshmee.sharepoint.com/sites/test1"
$context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$context.Credentials = $credentials
$rootWeb = $context.Web;
$context.Load($rootWeb);
DeleteVersionsFromLists($rootWeb);
$childWebs = $context.Web.Webs;
$context.Load($childWebs);
$context.ExecuteQuery();
foreach ($_web in $childWebs)
{
DeleteVersionsFromLists($_web);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment