PowerShell To Replace The Old Content Type With New One

One of our users came up with a request to exchange all the old content types with the new one.

If you Google it you will find lots of resources which can help you achieve it.

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

Below is the PowerShell to achieve it.

  1. Add - PSSnapin Microsoft.SharePoint.PowerShell# Custom PowerShell Function to  
  2. switch Content type of all items stored in a SharePoint library  
  3. Function Change - ItemContentType {  
  4.     param(  
  5.         [Microsoft.SharePoint.SPWeb] $Web = $(  
  6.             throw "Web URL!"), [string] $ListName = $(  
  7.             throw "ListName"), [string] $OldContentTypeName = $(  
  8.             throw "OldContentTypeName"), [string] $NewContentTypeName = $(  
  9.             throw " 'NewContentTypeName"))# Get the list  
  10.     $List = $Web.Lists[$ListName]# Get the new content type  
  11.     $NewContentType = $List.ContentTypes[$NewContentTypeName]# Iterate through each item in the list  
  12.     foreach($item in $list.Items) {  
  13.         if ($item.ContentType.Name - eq $OldContentTypeName) {#  
  14.             Change the content type  
  15.             $item["ContentTypeId"] = $NewContentType.Id  
  16.             $item.SystemUpdate()  
  17.             Write - host "Content type changed for item: "  
  18.             $item.id  
  19.         }  
  20.     }  
  21. }#Variables  
  22. for processing  
  23. $WebURL = "Site URL"  
  24. $ListName = "Library Name"  
  25. $ContentTypeName = "New Content type Name"#Get the Web and List  
  26. $Web = Get - SPWeb $WebURL  
  27. $List = $Web.lists.TryGetList($ListName)  
  28. if ($list - ne $null) {#Call the  
  29.     function to add content type  
  30.     Change - ItemContentType $web $list "Old Content type Name"  
  31.     "New Content type Name"  
  32. }  
Happy SharePointing.