Wednesday, January 21, 2015

SharePoint Powershell script to change content type of all documents in a document library

Problem:
The reason why I had to write this scrip is due to the requirement from one of my clients. They want to change the order of Office (Word/Excel) document properties while creating a document from document template.

Note: If document properties are not visible, you have to select Advance Properties to show the properties dialog box.



I have tried several options to change ordering of content type, as well as for the document library field but to no avail.

Finally, I decided to create a new content that has all the fields of the old content type but with different ordering when I changed the content type of document to new content type. It worked like a charm and solved the core issue.

The next task was to update all documents in a document library to have a new content type.

Other scenarios, where you can use this script when you have content type of documents in document library.

Script is provided below for reference.

# This script can be used to changed the content of all documents in a document library
Add-PSSnapin Microsoft.SharePoint.Powershell
$url = "http://sharept13dev1:1123/"
$site = Get-SPSite -Identity $url
$web = $site.OpenWeb()
$documentLibrary = $web.GetList("Draft")
$OldCTName = "Old Content Type"
$NewCTName = "New Content Type"
$oldCT = $documentLibrary.ContentTypes[$OldCTName]
$newCT = $documentLibrary.ContentTypes[$NewCTName]
$newCTID = $newCT.ID

$documentLibrary.Items | ForEach-Object {
    if ($_.File.CheckOutType -eq "None"){
        $item = $_
        $Editor = $item["Editor"]
        $Modified = $item["Modified"]
        $_.File.CheckOut()
        write-host "Resetting content type for file" $web "/" $_.Url "from" $oldCT.Name "to" $newCT.Name
        $_["ContentTypeId"] = $newCTID
        $item["Editor"] = $Editor
        $item["Modified"] = $Modified
        $_.Update()
        $_.File.CheckIn("Content type changed to " + $newCT.Name, 1)

    }
}
$site.Dispose()