Wednesday, January 25, 2012

Reorder field in existing Contentype withPowershell

if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"}))
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
clear
$dirURL = "Url of the Content Type"
$contentTypeName = "ContentTypeName"
$fieldInternalName= "Internal name of the field to reorder"
$field0BasedIndex = 8 #Position on the contentytpe this field is wanted

if($site -ne $null){
    $web = $site.RootWeb
    if($web -ne $null){
        $ct = $web.ContentTypes[$contentTypeName]
        if($ct -ne $null){
            write-Host "content Type Found"  -foregroundcolor green
           
            $fields = New-Object 'System.Collections.Generic.List[string]' ;
            [Microsoft.SharePoint.SPFieldLinkCollection]$flinks = $ct.FieldLinks;
            #Read all the InternalNames of the FieldLinks into a list
            foreach($fieldLink in $flinks){
             $fields.Add($ct.Fields[$fieldLink.ID].InternalName);
            }
            if($fields.Contains($fieldInternalName)){           
                write-Host "Field found in Content Type" -foregroundcolor green;
                $indexFound = $fields.IndexOf($fieldInternalName)
                if($indexFound -ne $field0BasedIndex )
                {
                    $fields.RemoveAt($indexFound)
                    #insert or append the field
                    if($field0BasedIndex -le $fields.Count -1){
                        $fields.Insert( $field0BasedIndex,$fieldInternalName)
                    }
                    else{
                        $fields.Add($fieldInternalName);
                    }
                    #Add the array to the reorder
                    $flinks.Reorder($fields.ToArray());
                    #Update the ContentYpe
                    $ct.Update($true)
                 }
            }
            else{
               write-Host "Field not found in Content Type" -foregroundcolor red;
            }
        }
        else{
            write-Host "Content type not found"  -foregroundcolor red
        }
        $web.Update()
        $web.Dispose();
    }
    $site.Dispose();
}

No comments:

Post a Comment