Forum Discussion
Removing 7days old files in Sharepoint folder.
I haven't been a SharePoint guy in over a decade meaning I'm unfamiliar with this community-based PowerShell module, but from taking a peek at the commandlet reference, it does appear you can shift the filtering process over to being server-side.
Having seen some exceedingly large custom lists in my time (circa 200,000 items), shifting the filtering to being server-side would allow your script to scale considerably higher.
While I know nothing of CAML, looking at example 6, it appears to have an error. In the Where clause, it opens with a <Geq> but incorrectly closes with an </Eq>, but that aside, it should serve as a useful example on how to shift the heavy lifting back over to SharePoint.
Here's my best guess (which I cannot test) at how I would look to move the workload:
- Define a CAML query string;
- Change line 19 to use the -Query parameter in conjunction with the CAML string;
- Remove lines 20 and 21.
CAML query string
CAML queries are case-sensitive so be sure to check this for errors.
For simplicity, I'm also using the <Today/> element. You can get more granular using the <Value/> element if you have the appetite.
$CamlQuery = @"
<View>
<ViewFields>
<FieldRef Name='Modified'/>
</ViewFields>
<Query>
<Where>
<Geq>
<FieldRef Name='Modified'/>
<Value Type='DateTime'>
<Today OffsetDays = '-7'/>
</Value>
</Geq>
</Where>
</Query>
</View>
"@
I'm unclear on whether the field is named "Modified" - as per the Get-PnPListItem reference I linked earlier, or if it's "ModifiedDate", as per your example code. I've left it as "Modified" as perhaps that is indeed what SharePoint knows it as (as distinct from what the commandlet returns it as, as names can vary), but you may need to change that as I can't test it.
I did find "Modified" listed as a base type here, but it's an old article and may no longer be accurate
Edited:
Just adding that the Microsoft literature does seem to confirm that the field to use is within the query is indeed named Modified, meaning it's the PnP commandlet changing Modified to ModifiedDate.
Change the Get-PnPListItem section in line 19
From this:
Get-PnPListItem -List Documents -FolderServerRelativeUrl $FolderServerRelativeUrl
To this:
Get-PnPListItem -List Documents -FolderServerRelativeUrl $FolderServerRelativeUrl -Query $CamlQuery
Here's some additional reference material
Cheers,
Lain
- Alan2022Sep 22, 2022Iron ContributorLainRobertson
Hi,
I never tried CAMLQuery.
But i think server side querying is also a good approach in filtering files in sharepoint.
Thanks i will add this in my next research.