During our O365 Migration, we had an issue with removing old content type at library level since the items are attached with the old content type, hence I wrote script to change the old content type with the new content type for each items.
In this article, let us see how to change the document content type for an existing item without changing/modifying the Modified by and Modified columns.
Note: Before changing the content type of your document/item, make sure that the content type you are going to change to is associated with the list or library. Otherwise you will get a generic error when loading your page.
Step 1: Make sure SharePoint dlls are available in your local folder
Step 2: Please provide the required inputs such as site URL, List Name, User Name and Password
#Load SharePoint CSOM Assemblies
cls
Add-Type -Path "C:PSdllMicrosoft.SharePoint.Client.dll"
Add-Type -Path "C:PSdllMicrosoft.SharePoint.Client.Runtime.dll"
#Variables for Processing
$SiteUrl = "https://ps.sharepoint.com/sites/test”
$ListName="test"
$UserName="test@test.onmicrosoft.com"
$Password ="****"
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Context.Credentials = $credentials
try{
#Filter and Get the List Items using CAML
$list = $Context.web.Lists.GetByTitle($ListName)
$Query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(1000);
$Items = $list.GetItems($Query);
#$listItem= $list.GetItemById(97709);
$Context.Load($list)
$Context.Load($list.ContentTypes)
$Context.Load($Items);
$Context.ExecuteQuery();
#Get the new content type ID for library/lsit
foreach($ct in $list.ContentTypes){
if($ct.Name -eq "Document"){
$contentTypeId= $ct.Id
}
}
Write-Host "New Content Type ID."+ $contentTypeId -ForegroundColor Green
foreach($listItem in $Items)
{
# Change the old content type with the new content type at item level and preserve the modified and Modified by
Write-Host "Item ID:"$listItem["ID"].ToString();
$Context.Load($listItem.ContentType)
$context.ExecuteQuery()
write-Host $listItem.ContentType.Name
if ($listItem.ContentType.Name -eq "Working Document")
{
$listItem["ContentTypeId"] = $contentTypeId.StringValue
$modifiedBy = $listItem["Editor"] #Editor is the internal name of the Modified By column
$listItem["Editor"] = $modifiedBy
$modified = $listItem["Modified"] #Modified is the internal name of the Modified column
$listItem["Modified"] = $modified
$listItem.Update()
}
}
$Context.ExecuteQuery()
write-host "Item Updated!" -foregroundcolor Green
}
catch{
write-host "$($_.Exception.Message)" -foregroundcolor red
}
Hope this helps!
Leave a comment