Two useful SharePoint Powershell links

Fri, Aug 22, 2014 2-minute read

I continue to do some work in SharePoint 2010 which means I continue to trip over weird issues.

Issue 1: Error creating content type. A duplicate content type was found.

Matt covers this issue:

If you’ve gotten this error and come to this site looking for answers, chances are it isn’t simply because the name you’re trying to give a new content type is already in use. On the contrary, you are probably sitting there saying that you know without a doubt the name you are entering is not in use, and you have probably even pounded a random value out on your keyboard just to prove the point.

Maybe you’ve come across forum posts like the following that suggest you make an update directly to the content database (MSDN Forum Post). I never go this route, because it is going to take you out of support with Microsoft, since working with the database is specifically prohibited.

The issue is a bug in how SharePoint is assigning IDs to new content types. Read his post for more details.

Fortunately, he posts an excellent Powershell script to overcome it:

function FixContentTypeForChildCreation
{
    param(
    [Microsoft.SharePoint.SPWeb]$web,
    [Microsoft.SharePoint.SPContentType]$ct
    )
 
    #Grab the ID of the CT you need to fix for child creation
    $ctID = $ct.ID.ToString();
 
    for($i=0;$i -lt 10; $i++)
    {
        #Create a new child content type with a unique guid and then delete it
        $newCTID = new-object Microsoft.SharePoint.SPContentTypeId($ctID + "00" + [Guid]::NewGuid().ToString("n"));
        $newCT = new-object Microsoft.SharePoint.SPContentType($newCTID, $web.ContentTypes, "Temp Content Type - Auto Deleted");
        $addedCT = $web.ContentTypes.Add($newCT);
        $newCT.Delete();    
    }
 
    Write-Host "Content Type Fix for Child Creation is Complete"
}

Perfect.

Issue 2: Iterating large lists in Powershell

Iterating large lists is a common and well known issue in SharePoint, since using the .Items collection of the .GetItems method will either hit throttle limits or suck up all available memory and crash your server. Use of the query position indicator in .NET is the common fix. But how do you go about this in Powershell? Well, with pretty much identical code, thanks to Kirk’s blog post at MSDN.

$web = Get-SPWeb http://portal.sharepoint.com
$list = $web.Lists["LargeList"]

$spQuery = New-Object Microsoft.SharePoint.SPQuery
$spQuery.ViewAttributes = "Scope='Recursive'";
$spQuery.RowLimit = 2000
$caml = '<orderby Override="TRUE"><fieldref Name="ID"></fieldref></orderby>' 
$spQuery.Query = $caml 

do
{
    $listItems = $list.GetItems($spQuery)
    $spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
    foreach($item in $listItems)
    {
        Write-Host $item.Title
    }
}
while ($spQuery.ListItemCollectionPosition -ne $null)

Thanks both - you saved me a bunch of time.