PowerShell SharePoint Updating list item Authors and Editors

Notice this code snippet assumes that you have already retrieved your list item also this code can be used to keep the original author and editor of an item while making changes to list items through a script with admin privileges.

Also notice that for some reason I had to use on the item level Update() instead of SystemUpdate(). No idea why, very weird since I know that on C# it is definitely SystemUpdate() to be used if you want to preserve the original editor.

Anyway here is the code snippet:

$author = $item["Author"]
 $editor = $item["Editor"]

Write-Host "Original author: " $author
 Write-Host "Original editor: " $editor
 $authorLogin = New-Object Microsoft.SharePoint.SPFieldUserValue ($web, $author)

 $editorLogin = New-Object Microsoft.SharePoint.SPFieldUserValue ($web, $editor)
 $itemOwners = $list.GetItemById($item.ID)
 $replacedUserAuthor =$web.EnsureUser($authorLogin.User.LoginName)
 $replacedUserEditor =$web.EnsureUser($editorLogin.User.LoginName)

 #$replacedUserAuthor = get-SPuser -Web $web -Identity $authorLogin.User.LoginName
 #$replacedUserEditor =get-SPuser -Web $web -Identity $editorLogin.User.LoginName

 Write-Host "Updating the author field with: " $replacedUserAuthor
 Write-Host "Updating the editor field with: " $replacedUserEditor
 $itemOwners["Author"] = $replacedUserAuthor;
 $itemOwners["Editor"] = $replacedUserEditor;

 Also another snippet on how to print a full stack trace in powershell. The magic key is the “format-list –force” command after the exception:

#your code logic here
 Add-Content $filename $_.Exception |format-list –force
 Write-Host -ForegroundColor Red $_.Exception |format-list –force

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s