I am looking to run a script nightly to delete zip files older than 7 days. In Documents I have a folder called folder1 and inside that folder there are subfolders containing zip files. I have seen examples for sites/lists but not folders. The following cold will return:
But I would like to recursively delete all zip files in folder1 that are over 7 days old.
Try {
#Setup the context
$securePassword = ConvertTo-SecureString $SPOnlinePassword -AsPlainText -Force
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($SPOnlineUserName, $securePassword)
#Get the List
$List = $Context.Web.lists.GetByTitle($ListName)
#Define CAML Query to Filter
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXML = "<View Scope=RecursiveAll>
<Query>
<Where>
<And>
<Contains>
<FieldRef Name='FileLeafRef' /><Value Type='Text'>.zip</Value>
</Contains>
<Leq>
<FieldRef Name='Created' Type='DateTime'/>
<Value Type='DateTime'>
<Today OffsetDays='-7'/>
</Value>
</Leq>
</And>
</Where>
</Query>
</View>"
#Get List Items
$ListItems = $List.GetItems($Query)
$Context.Load($ListItems)
$Context.ExecuteQuery()
Write-host -f Green "Number of List Items Found:"$ListItems.Count
write-host $ListItems.Name
#Get Each Item's Created Date
$ListItems | ForEach-Object { Write-host ("List Item:{0} was created on {1}" -f $_["FileLeafRef"], $_["Created"]) }
foreach ($item in $ListItems) {
$List.getItemById($item.id).deleteObject()
}
$Context.ExecuteQuery()
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}
Edit: I have the above code sort of working until I received 'Error: Exception calling "ExecuteQuery" with "0" argument(s): "The operation has timed out."'