Tuesday, 22 November 2016

PowerShell to replace the old content type with new one.

One of our user came up with a request to change all the old content type with the new one.

If you do google you will find lots of resource which can help you achieve it.

But our user had special request while changing the content type, the modified by or modified time should not be changed.

Below is the PowerShell to achieve it.

Add-PSSnapin Microsoft.SharePoint.PowerShell

#Custom PowerShell Function to switch Content type of all items stored in a SharePoint library

Function Change-ItemContentType {
        [Microsoft.SharePoint.SPWeb]$Web = $(throw "Please provide the 'Web' Parameter!"),
        [string]$ListName = $(throw "Please provide the 'ListName' Parameter!"),
        [string]$OldContentTypeName = $(throw "Please provide the 'OldContentTypeName' Parameter!"),
        [string]$NewContentTypeName = $(throw "Please provide the 'NewContentTypeName' Parameter!")
    #Get the list
    $List = $Web.Lists[$ListName]

    #Get the new content type
    $NewContentType = $List.ContentTypes[$NewContentTypeName]
    #Iterate through each item in the list
    foreach($item in $list.Items)
        if($item.ContentType.Name -eq $OldContentTypeName)
            #Change the content type
            $item["ContentTypeId"] = $NewContentType.Id
            Write-host "Content type changed for item: "$item.id

#Variables for processing
$WebURL ="Site URL"
$ListName ="Library Name"
$ContentTypeName ="New Content type Name"

#Get the Web and List
$Web = Get-SPWeb $WebURL
$List = $Web.lists.TryGetList($ListName)

if($list -ne $null)
    #Call the function to add content type
    Change-ItemContentType $web $list "Old Content type Name" "New Content type Name"

Happy SharePointing :)

No comments:

Post a Comment