SharePoint Online: How to Delete a Folder using PowerShell?

Requirement: Delete a folder in SharePoint Online using PowerShell.
SharePoint Online PowerShell to Delete Folder

How to delete a folder in SharePoint Online?
Simply select the folder from the list or library, and then you can delete a folder either from the toolbar "delete" button or from the context menu's delete option.
SharePoint Online PowerShell Delete Folder
Confirm the delete prompt and you are done! now, let us delete the SharePoint Online folder using PowerShell.

SharePoint Online PowerShell to Delete Folder
Here is the PowerShell to remove a folder from a list or library in SharePoint Online. This PowerShell deletes folder with its contents including files and sub-folders.
Import-Module Microsoft.Online.SharePoint.Powershell -DisableNameChecking
#Variables for Processing
$SiteUrl = ""
$FolderURL="Shared Documents/Project 2020"

Try {
    #Get Credentials to connect
    $Cred = Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
    $Ctx.Credentials = $Credentials
    $Web = $Ctx.Web

    #Get the folder object from given URL
    #sharepoint online powershell delete folder in document library

    Write-host "Folder deleted Successfully!" -ForegroundColor Green
Catch {
    write-host -f Red "Error deleting Folder!" $_.Exception.Message
This script deletes the folder permanently. You can use $Folder.Recycle() method to send the folder to the recycle bin. Similarly, you can delete any sub-folder by setting the FolderURL parameter in the above script.

Delete SharePoint Online Folder using PnP PowerShell
We can also use this PnP PowerShell script to delete a folder in SharePoint Online:
#Config Variables
$SiteURL = ""
$FolderName = "Team Documents"
$ParentFolderSiteRelativeURL= "/Shared Documents"

#Get Credentials to connect
$Cred = Get-Credential

Try {
    #Connect to PNP Online
    Connect-PnPOnline -Url $SiteURL -Credentials $Cred
    #sharepoint online powershell delete folder
    Remove-PnPFolder -Name $FolderName -Folder $ParentFolderSiteRelativeURL -Force -Recycle -ErrorAction Stop
    Write-host -f Green "Folder '$FolderName' Deleted Successfully!"

catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
Getting "You have to delete all the items in this folder before you can delete this folder." error message? Well, this could be because of the retention hold policy applied to your site. Here is another script to bulk delete a folder and its contents SharePoint Online: Delete All Files and Sub-Folders from a Folder Recursively using PowerShell

1 comment:

  1. I want to bulk delete folders, How to do it? can you post PowerShell script please. TIA


Please Login and comment to get your questions answered!

Powered by Blogger.