I have a need to run a PowerShell script against a list that deletes items older than 15 days. I have the script written, as well as user notifications, however I am puzzled as to how I can recycle the item as the owner of the document.

This is simplified for the sake of the question, but this is the basic operation going on.

$fileage = 15
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$query.RowLimit = 2000;
$query.Query = '<OrderBy><FieldRef Name="Occurred" /></OrderBy><Where><Lt><FieldRef Name="Modified" /><Value Type="DateTime"><Today OffsetDays="-' + $fileAge + '" /></Value></Lt></Where>'
$listItems = $list.GetItems($query)
ForEach($file in $listItems){$item.Recycle()}

Now all the items in that list end up in the recycling bin of the user I ran the command under. Is it possible to take those files and move them into a specific user's bin?

up vote 2 down vote accepted

You should be able to impersonate the user, but will involve opening up a web object for each specific user.

$user=$web.AllUsers.GetByID(28)
$token = $user.UserToken;
$impWebObj= New-Object Microsoft.SharePoint.SPSite($web.Url, $token);
$imperWeb = $impWebObj.OpenWeb();
$list = $imperWeb.Lists["SPLISTNAME"]
$fileage = 15
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$query.RowLimit = 2000;
$query.Query = '<OrderBy><FieldRef Name="Occurred" /></OrderBy><Where><Lt><FieldRef Name="Modified" /><Value Type="DateTime"><Today OffsetDays="-' + $fileAge + '" /></Value></Lt></Where>'
$listitems = $list.GetItems($query)
ForEach($file in $listItems){
  $item = list.GetItemsByID($file.ID)
  $item.Recycle()

}
$imperWeb.Dispose()
$impWebObj.Dispose()

There may be a less taxing way of doing this, but that's the idea I came up with.

Source: http://sharing-the-experience.blogspot.com/2011/04/powershell-and-sharepoint-impersonation.html

EDIT: If it's a specific user, you can get the user by ID...

  • This is good, thanks! – Taylor Dec 17 '14 at 18:54

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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