Wednesday, January 25, 2012

Insert new Site Column in existing Contentype with PowerShell

# Check if Snap-in is loaded
if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$dirURL = "Type here the abolute Url to the Sitecollection where the contentytpe is defined"
$contentTypeName = "Traktandum"
$fieldId = [Guid]"{516ae749-c8b4-4a9b-858f-50881aae4165}"  
#fieldId mus match the one on the fieldXML

$site = Get-SPSite -Identity $dirURL
if($site -ne $null){
    $web = $site.RootWeb
    if($web -ne $null){
        #Assign fieldXML variable with XML string for site column
        $fieldXML = '<Field
    Description="$Resources:MyCustom,Field_MyPortalOtherGuest_Description"
    DisplayName="$Resources:MyCustom,Field_MyPortalOtherGuest_DisplayName"
    Hidden="FALSE"
    Name="SomeName"
    Title="SomeName"
    Required="FALSE"
    Sealed ="FALSE"
    Sortable="FALSE"
    List="UserInfo"
    ShowField="ImnName"
    Mult="TRUE"
    Type="UserMulti"
    UserSelectionMode="0"
    UserSelectionScope="0"
    ID="{516ae749-c8b4-4a9b-858f-50881aae4165}"
    Group="$Resources:MyCustom,Field_Group"
    StaticName="SomeName" />'
    
        #Add the field to the web
        $web.Fields.AddFieldAsXml($fieldXML)
        $web.Update()

        $field = $web.AvailableFields[$fieldId]
        $ct = $web.ContentTypes[$contentTypeName]
        if($field -ne $null -and $ct -ne $null){
            #Delete any existing Field with that ID from the ContentType
            $ct.FieldLinks.Delete($fieldId)
            #Update the Contentype includeing childs
            $ct.Update($true, $true)
            #Creat a new SPFieldLink for that field and insert it to the ContentType
            $link = new-object Microsoft.SharePoint.SPFieldLink $field            
            $ct.FieldLinks.Add($link)
            $ct.Update($true, $true)
        }
        $web.Update()
        $web.Dispose()
    }
$site.Dispose()
}

No comments:

Post a Comment