Skip to main content

Recursively remove a folder from OneDrive with PowerShell

· 2 min read

Did you know, when you have a retention policy configured for OneDrive in Microsoft 365 you lose the ability to recursively delete folders. The OneDrive client often handles this by recursing through the folder tree to remove the online copies but sometimes that doesn't work and in those cases you can end up stuck with a folder tree that you would have to manually recurse to remove the offending folders by first emptying them entirely before OneDrive will let you delete them.

Well that's never going to happen ;-)

Enter PowerShell.

Required Modules

You'll need the PnP.PowerShell module for this script. Install with Install-Module 'PnP.PowerShell'

The script

Remove-OneDriveFolderRecursively.ps1
loading...

Invoking the script

The script is looking for three parameters, an example invocation to remove a synced "Documents/PowerShell/Modules" folder in Satya Nadella's OneDrive would be:

Double the Documents

You'll notice below that the /Documents folder in the path is doubled. This is because the first folder in the OneDrive path is always /Documents then your path starts. In this example we're removing the /Documents/PowerShell/Modules folder.

Remove-OneDriveFolderRecursively -OneDriveHost 'https://microsoft-my.sharepoint.com' -SitePath '/personal/satya_nadella_microsoft_com' -FolderPath '/Documents/Documents/PowerShell/Modules'

Hope this helps!

This post was inspired by a script posted on Microsoft's TechCommunity here...