Tuesday, 26 February 2013

Change Values at "Read-Only" fields

A - OBJECTIVE: to complete a proper data migration with correct authors & editors ("Created By" & "Modified By")

B - PROBLEMS :

Admins cannot "edit" Read-Only fields at SharePoint in a straight-forward method.

C - SOLUTION:

As an admin, you can open Powershell and run the below code to update these Read-Only fields:

Experiment 1: to update Modified Time, Created Time, Author & Editor

$author = New-Object Microsoft.SharePoint.SPFieldUserValue($web,”1111;#User Display Name”)  #1111 is User ID in All People List
$item[“Author”] = $author
$item.Properties[“vti_author”] = $author.User.LoginName
$item[“Editor”] = $author
$item.UpdateOverwriteVersion()

Result : Successful

Experiment 2: to update File/Folder Name, Modified/Created Time & Author/Editor

First Try:


# get the original metadata
$personEditor = $Folder.Item["Editor"]
$timeModified = $Folder.Item["Modified"]

# update the folder name
$Folder.Item["Name"] = "New Name"

# revert the original metadata back
$Folder.Item["Editor"] = $personEditor
$Folder.Item["Modified"] = $timeModified

$Folder.Item.UpdateOverwriteVersion()

Result : Failed (Folder Name is updated but Modified Time & Editor are not updated)

Second Try:

# get the original metadata
$personEditor = $Folder.Item["Editor"]
$timeModified = $Folder.Item["Modified"]

# update the folder name
$Folder.Item["Name"] = "New Name"

# THIS LINE IS IMPORTANT TO BE ADDED IN
$Folder.Item.UpdateOverwriteVersion()

# revert the original metadata back
$Folder.Item["Editor"] = $personEditor
$Folder.Item["Modified"] = $timeModified

$Folder.Item.UpdateOverwriteVersion()

Result : Successful (All fields are updated properly).

D - SOURCE CODE:

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
$site = New-Object Microsoft.SharePoint.SPSite(“http://sharepoint/subsite”)
$web = $site.OpenWeb()
$doclib = $web.Lists[“TestDocLib”]
Write-Host “SharePoint Object: ” $doclib.basetype
foreach($item in $doclib.Items){
Write-Host “Created By – Old Value: ” $item[“Author”]
$author = New-Object Microsoft.SharePoint.SPFieldUserValue($web,”1111;#User Display Name”)  #1111 is User ID in All People List
$item[“Author”] = $author
$item.Properties[“vti_author”] = $author.User.LoginName
$item[“Editor”] = $author
$item.UpdateOverwriteVersion()
Write-Host “Created By – New Value: ” $item[“Author”]
}

No comments:

Post a Comment