views:

1934

answers:

3

I need a script which can delete all files which are older than a day and this script needs to be invoked every day automatically in the Sharepoint server. How can i do this and any hints as how to write the script?

A: 

You could create a custom timer job in SharePoint using .NET and the WSS API to do the job. Use the SPQuery class to query files by date in a document library. Use the SPSiteDataQuery class if you need to query across multiple document libraries.

Lars Fastrup
A: 

If you really need a script rather than writing code (such as a timer job) then use Powershell to access the SharePoint .NET objects with a scripting engine. Once you've written the script, set up a Windows scheduled task to run it every day.

In the script follow Lars' guidance on using one of those two query classes. Then from the query results you can obtain a reference to each SPListItem you'd like to delete. Either use SPListItem.Delete or SPListItem.Recycle to remove the item.

Here's an example that uses SPQuery:

[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

$site = new-object Microsoft.SharePoint.SPSite("http://yoursite/")
$web = $site.OpenWeb("Web Title")
$documentLibrary = $web.Lists["Document Library Name"]

$yesterdaysDate = [Microsoft.SharePoint.Utilities.SPUtility]::CreateISO8601DateTimeFromSystemDateTime([System.DateTime]::UtcNow.AddDays(-1.0))
$query = new-object Microsoft.SharePoint.SPQuery
$query.ViewFields = "<FieldRef Name='Modified' />"
$query.Query = "<Where><Leq><FieldRef Name='Modified' /><Value Type='DateTime' IncludeTimeValue='TRUE'>" + $yesterdaysDate + "</Value></Leq></Where>"
$queryItems = $documentLibrary.GetItems($query)
foreach ($item in $queryItems)
{
    echo $item.Url
    $item.Delete()
}
$web.Dispose()
$site.Dispose()
Alex Angas
+2  A: 

I think an easier way to do it would be to create a site collection policy with an expiration. Set the retention period for one day. You can then attach the disposition workflow to your list which acn be used to clean these files up. You should be able to do all of this without writing any code.

Here is a link with more information about disposition workflow. http://office.microsoft.com/en-us/sharepointserver/HA101544291033.aspx

Thanks, Corey

Corey Roth