1

Morning Everyone,

I'm new in scripting so I'm looking for the small help. I have one case where I need to delete newest folders with the subfolders and the subfolders... and so on in the Library. I searched for the PS code and I found something that it realy can helps me but this code delete everything in library, I have no clue how to create and put function which will listed me only newest folders (they have to be not older than 6 weeks) because i need to delete only the newest so i can't delete all folders from there. Please help me with this.

PS. If you have some books or ebooks that could help get me better known with the scripting in sharepoint, please write me. Thanks

 
#Function to Delete all files in a Folder    
Function Delete-AllFilesFromLibrary([Microsoft.SharePoint.SPFolder]$Folder)
{
    #Delete All Files in the Folder
    Foreach ($File in @($Folder.Files))  
    {
        #Delete the file
        $File.Delete() | Out-Null
 
        Write-host -f Green "Deleted File '$($File.Name)' from '$($File.ServerRelativeURL)'"
    }
 
    #Delete files in Sub-folders
    Foreach ($SubFolder in $Folder.SubFolders | where {$_.Name -ne "Forms"})
    {
        #Call the function recursively
        Delete-AllFilesFromLibrary($SubFolder)
    }
 
    #Delete folders
    ForEach ($SubFolder in @($Folder.SubFolders))
    {
        #Exclude "Forms" and Hidden folders
        If(($SubFolder.Name -ne "Forms") -and (-Not($SubFolder.Name.StartsWith("_"))))
        {
            #Delete the Sub-Folder
            $SubFolder.Delete() | Out-Null
            Write-host -f Green "Deleted Folder '$($SubFolder.Name)' from '$($SubFolder.ServerRelativeUrl)'"
        }
    }
}
 

$Web = Get-SPWeb "intranet.com/sales"
$Library = $Web.Lists.TryGetList("Documents")
 

Delete-AllFilesFromLibrary $Library.RootFolder ```

1 Answer 1

0

Marek: You can compare the created date of each item with the current date minus 6 weeks (let's call this $compare_date). If the created date of the file is GREATER than the compare date, delete it. So wrap your current code around this comparison:

# Get all items in the library
$Items = (Get-PnPListItem -List $list_name  -PageSize 2500).FieldValues 
$six_weeks_ago = -7*6   

# get today's date and subtract 6 weeks
[datetime]$compare_date = (get-date).addDays($six_weeks_ago) 

foreach($Item in $Items){
  if([datetime]$Item.Created -ge $compare_date){
      'Delete this object'
  }
}
2
  • Thank you so much! I’m really grateful to you, I will check it in monday. Have a nice weekend. Faith in peoples return to me :)
    – marek -
    Commented Apr 23, 2022 at 9:09
  • You're welcome. Commented Apr 23, 2022 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.