Delete OneDrive Folders Using PowerShell Commands

Hello,

I'm using PowerShell with PnP to delete a folder named "Test migration" from users' OneDrive accounts.

These accounts contain numerous folders, subfolders, and files.

Due to retention being enabled, I'm deleting root files and folders first, then moving up the folder hierarchy. However, this process takes a significant amount of time, even for users with only 1 GB of files.

Is there a way to speed up this process or an alternative scripting solution?

The main commands I'm using are:

Remove-PnPFile -ServerRelativeUrl $file.ServerRelativeUrl -Force -Recycle

Remove-PnPFolder -Name $subfolder.Name -Folder $parentFolderUrl -Force -Recycle

Any assistance would be greatly appreciated.

To speed up the process of deleting folders and files from numerous users’ OneDrive accounts, consider the following steps:

  1. Optimize Your Script

    • Avoid creating unnecessary arrays of objects.
    • Remove any objects that you don’t need.
    • Forgo the Sort-Object command as the order of deletion is not crucial.
    • Use pipelining instead to improve efficiency.
  2. Use Batch Requests

    • Leverage Invoke-PnPBatch to send multiple commands at once.
    • This can significantly reduce the number of requests to the server, and hence the time taken.
  3. Parallelize the Process

    • If possible, run the script in parallel for different users.
    • This can further speed up the process by distributing the load.
  4. Disable Retention Temporarily

    • If allowed by your organizational policies, temporarily disable retention to speed up the deletion process.
  5. Verify Folder Paths

    • Make sure the folder paths being passed are correct, especially considering the subfolders.
  6. Clear the Recycle Bin

    • After deletion, use Clear-PnPRecycleBinItem -All -Force to permanently remove items from the Recycle Bin, reducing future storage issues.
  7. Avoid Overcrowding the Recycle Bin

    • If deleting a large number of items, clear the Recycle Bin regularly during the process to avoid exhausting available space.

By following these guidelines, you can optimize your PowerShell script to delete folders and files more efficiently, thus reducing the overall time taken.