Unable to delete empty folder (Access to the cloud file is denied)

Viewed 957

In a PS script recursively deleting empty folders using Remove-Item, I get the exception "Access to the cloud file is denied" for some of the empty folders.

1 Answers

Even if I didn't have OneDrive installed, the solution $dir.Delete($true) from this article https://evotec.xyz/remove-item-access-to-the-cloud-file-is-denied-while-deleting-files-from-onedrive/ worked

    $directoriesToDelete = Get-ChildItem -Path $pathToPictures -Recurse -Directory
foreach ($directoryToDelete in $directoriesToDelete) {
    $pathToDirectory = $directoryToDelete.FullName
    if ((Get-ChildItem $pathToDirectory | Measure-Object).Count -eq 0) {
        try {
            Remove-Item $pathToDirectory -Force
            Add-LogEntry -PathToLog $logFile -LogEntry "$pathToDirectory deleted"
        } catch {
            if ($_.Exception.Message -eq 'Access to the cloud file is denied') {
                $dir = Get-Item -LiteralPath $pathToDirectory
                try {
                    $dir.Delete($true)
                } catch {
                    Add-LogEntry -PathToLog $logFile -LogEntry "Error deleting '$pathToDirectory' (using dir.Delete): $_"
                }
            } else {
                Add-LogEntry -PathToLog $logFile -LogEntry "Error deleting '$pathToDirectory': $_"
            }
        }
    }
}
Related