PowerShell Tip: SharePoint Online - CSOM - Don't Delete Contents but Just Recycle It

Introduction

Deleting and Restoring SharePoint Lists, Document Libraries, Items, Site or Web, etc. is a quite common task for SharePoint IT Professionals. As part of the daily operations, we assist SharePoint Power Users to manage the contents. But, when we need to delete multiple items using the GUI is not the best option so we use PowerShell or some other program to do bulk operations.

The deleted items are moved to the recycle bin if we use the GUI but using PowerShell or CSOM it will be completely removed. It means we can't restore from the recycle bin of the site or site collections.

In this TechNet Wiki, we will show a PowerShell tip to remove the SharePoint List from the site and make it available in the recycle bin so you can restore it when needed.

References

Solution

The tip is to use $List.Recycle() instead of $List.DeleteObject(). $List.Recycle() moves the list to the recycle bin and returns the GUID value of the recycle bin item. To suppress the GUID, we used [void] type cast while calling the $List.Recycle() Let's see the PowerShell code block which does the trick.

try
{
    $SPOClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($Url)
    $SPOClientContext.Credentials = [Microsoft.SharePoint.Client.SharePointOnlineCredentials]::new($Credential.UserName,$Credential.Password)
    $List = $SPOClientContext.Web.Lists.GetByTitle($Title)
    [void]$List.Recycle()
    $SPOClientContext.ExecuteQuery()
}
catch
{
    $_.Exception.Message
}

Output

Code

Import-Module 'C:\Program Files\NuGet\Packages\Microsoft.SharePointOnline.CSOM.16.1.5312.1200\lib\net45\Microsoft.SharePoint.Client.dll'
Import-Module 'C:\Program Files\NuGet\Packages\Microsoft.SharePointOnline.CSOM.16.1.5312.1200\lib\net45\Microsoft.SharePoint.Client.Runtime.dll'
function Remove-xSPOList
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)]
        $Url,
 
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        $Title,
 
        [Parameter(Mandatory)]
        [System.Management.Automation.CredentialAttribute()]
        [pscredential]
        $Credential
    )
    process
    {
        try
        {
            $SPOClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($Url)
            $SPOClientContext.Credentials = [Microsoft.SharePoint.Client.SharePointOnlineCredentials]::new($Credential.UserName,$Credential.Password)
            $List = $SPOClientContext.Web.Lists.GetByTitle($Title)
            [void]$List.Recycle()
            $SPOClientContext.ExecuteQuery()
        }
        catch
        {
            $_.Exception.Message
        }
    }
}
Remove-xSPOList -Url https://chensoffice365.sharepoint.com -Title "PowerShellDemo" -Credential "Chendrayan@contoso.onmicrosoft.com"