Tuesday 12 May 2015

PowerShell Script : Change content type for all documents in a library

I had come up this requirement after migration. The old migrated library is populated with thousands of files having the default content type set to ‘Document’. All the documents now need to be assigned a specific content type.
If we have a large library Powershell is the easy way to change the content type. Before you run the script, make sure the new content type is associated with the library.
The script below sets up a function which will look at the document library and modify all files associated with the specified content type to a different one.

'Drop Off Library' is my library name and want to update all files associated with 'Document' content type to 'Techsheet'.

if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}
$webUrl = "http://server:portno/sites/yoursite"
$web = Get-SPWeb $WebUrl
$list = $web.Lists["Drop Off Library" #Library Name
$oldCT = $list.ContentTypes["Document" #Old Content Type Name
$newCT = $list.ContentTypes["Techsheet" #New Content Type Name
$newCTID = $newCT.ID
write-host $newCTID
for($i=0; $i -le $web.Lists.Count; $i++)
    {
    foreach($item in $list.items[$i])
        {
        if ($item.ContentType.Name -eq $oldCT.Name)
            {
                 #Check the check out status of the file
                if ($item.File.CheckOutType -eq "None")
                {
                    #Change the content type association for the item
                    $item.File.CheckOut()
                    write-host "Resetting content type for file" $item.Name "from" $oldCT.Name "to" $newCT.Name
                    $item["ContentTypeId"] = $newCTID
                    $item.Update()
                    $item.File.CheckIn("Content type changed to " + $newCT.Name, 1)
                }
            }
        }
    }
$web.Dispose()