Friday, 26 October 2012

Change the content type of list items using PowerShell

If you've got a content type deployed in multiple lists in site, and you want a way to quickly change all the existing items to the new content type, you can use PowerShell to do the dirty work.

Note that there are a few caveats to this:
1. The default content type of the list isn't being changed by the script
2. If you change the content type of items, and the new content type has new fields that are require fields, users will be prompted to enter information into the required fields next time they edit the item.
3. You need to add the new content type to each list that will be updated, before running this script

Firstly, if you want to understand how many items are going to be updated, run this script, which will report the number of list items to be updated for each list.

List items that need changing:

$oldCtName = "theNewContentTypesName";
$newCtName = "theOldContentTypesName";
$w = get-spweb http://my;
$a = $null;
$a = @();
$lc = $w.Lists;
foreach($l in $lc){
$lT = $l.Title;
if($l.ContentTypesEnabled -eq $false){continue;}
if($l.IsContentTypeAllowed($contenttype) -eq $false){continue;}
$cT = $l.ContentTypes[$newCtName];
if($cT -eq $null){continue;}
$ic = 0;
$listitems = $l.Items;
$listname = $l.Title;
Write-Host "Found Content Type:"$cT.Name"on list $listname";
foreach($i in $listitems){
if($i["Content Type"] -eq $oldCtName){$ic++;}
};
if($ic -gt 0){
$a += ("List $listname has $ic items which have been updated with the new content type.")
};
}
$a


To update the content type for each list item (in each list in the web that has your new content type added to it), use the following script:

Change Content Type

$oldCtName = "theNewContentTypesName";
$newCtName = "theOldContentTypesName";
$w = get-spweb http://my;
$CtypeId = [Guid]("{03e45e84-1992-4d42-9116-26f756012634}") #SPBuiltInFieldId.ContentTypeId
$a = $null;
$a = @();
$lc = $w.Lists;
foreach($l in $lc){
$lT = $l.Title
if($l.ContentTypesEnabled -eq $false){
Write-Host "Content Types are not enabled on the $lT list";
continue;
}
if($l.IsContentTypeAllowed($contenttype) -eq $false){
Write-Host "Content Type not allow on the $lT list";
continue;
}
$cT = $l.ContentTypes[$newCtName];
if($cT -eq $null){
Write-Host "Content Type has not been added to this list. Skipping to the next list.";
continue;
}
Write-Host "Found Content Type:"$cT.Name;
$ic = 0;
$listitems = $l.Items
$listname = $l.Title;
foreach($i in $listitems){
if($i["Content Type"] -eq $oldCtName){
$i[$CtypeId] = $cT.Id;$i.SystemUpdate();$ic++;
}
};
if($ic -gt 0){
$a += ("List $listname has $ic items which have been updated with the new content type.")
};
}
$a

No comments:

Post a Comment