I want to delete empty folders which are nested under a folder which is called “Archiv” from SharePoint Online. My aim is to delete every folder which is loacted under a folder called “Archiv” and has no documents. If all subfolders of an “Archiv”- folder are empty I also want to delete the folder “Archiv”.
If possible I´d linke to get the results within an .csv to proof which folders has been deleted.
That’s a nice task to practice on. Do you have any question regarding this task?
Please have in mind that we do not write ready to use code or solutions on request. We expect you to make an own attempt to achive a given task at first.
If you search on google for “delete empty folders sharepoint online” there are some promissing search results:
thanks for the warm welcome =)
Honestly I´ve already had some attemps but I even if I´m trying to run code in PowerShell ISE (i.e the code which is under the link you provided) I´m just getting errors in the output screen. (in this case it shows: "the remote server gave back an error. Seems that there is a problem with $web = Get-WebPnPWeb).
I was using this code to achieve my goal but then I realised that it will not work for sharepoint online =(
$LogFile = 'C:\Users\User\Desktop\Deleted.csv'
$TopDir = 'C:\Users\User\Path'
# first get a list of all folders below the $TopDir directory that are named 'Archiv' (FullNames only)
$archiveDirs = (Get-ChildItem -LiteralPath $TopDir -Filter 'Archiv' -Recurse -Directory -Force).FullName |
# sort on the FullName.Length property in Descending order to get 'deepest-nesting-first'
Sort-Object -Property Length -Descending
# next, remove all empty subfolders in each of the $archiveDirs
$removed = foreach ($dir in $archiveDirs) {
(Get-ChildItem -LiteralPath $dir -Directory -Force -Recurse) |
# sort on the FullName.Length property in Descending order to get 'deepest-nesting-first'
Sort-Object @{Expression = {$_.FullName.Length}} -Descending |
ForEach-Object {
# if this folder is empty, remove it and output its FullName for the log
if (@($_.GetFileSystemInfos()).Count -eq 0) {
$_.FullName
#Remove-Item -LiteralPath $_.FullName -Force
}
}
#next remove the 'Archiv' folder that is now possibly empty too
if (@(Get-ChildItem -LiteralPath $dir -Force).Count -eq 0) {
#output this folders fullname and delete
$dir
#Remove-Item -LiteralPath $dir -Force
}
}
$removed | Set-Content -Path $LogFile -PassThru # write your log file. -PassThru also writes the output on screen