There are times when you need to bulk delete all files from a number of users OneDrive, such as after a migration that has had some unexpected results and it is easier to start again.
This script:
- Takes a text file of email addresses (each on a new line) as the input
- Gets credentials to authenticate
- Determines the OneDrive URL for the user account
- Gets all the items in the OneDrive “Documents” folder and deletes them.
# Set Config Parameters
# List of email address of users whose OneDrive to be purged
$UserEmailsListData = "PathToFileWithListofEMails.txt"
# Admin Site URL
$AdminSiteURL = "https://<tenantname>-admin.sharepoint.com"
$PageSize = 500
# Get Credentials to connect
$Credential = Get-Credential
# Get the email addresses from the text file
$UserEmailsList = Get-Content $UserEmailsListData
foreach ($U in $UserEmailsList){
$UserAccount = $U
#Connect to the site
Connect-PnPOnline $AdminSiteURL -SPOManagementShell -Credentials $Credential
# Get OneDrive url from email address
$PersonalURL = (Get-PnPUserProfileProperty -Account $UserAccount).PersonalUrl
# Connect to the OneDrive
Connect-PnPOnline –Url $PersonalURL -Credentials $Credential
# Get the items in the users OneDrive
$Items = Get-PnPListItem -List "Documents" -PageSize $PageSize
if ($null -ne $Items){
foreach ($item in $items) {
try {
Remove-PnPListItem -List "Documents" -Identity $item.Id -Force
Write-Output "Deleting Item - "ID:"$($item.Id) - "File:"$($item.FieldValues.FileRef)"
}
catch {
#Write-Output "Error Occurred While Deleting the Item from OneDrive"
}
}
}
else {
Write-Output "OneDrive empty for user $UserAccount"
}
}