Wednesday, August 24, 2011

PowerShell Script: Add a Site Column to Multiple Content Types




I needed to add a single column to multiple content types but couldn't add it to the parent because not all of the child content types needed this new column.  PowerShell to the rescue!

Obviously I created the site column first...  Then I used an import file and a ForEach loop to read each content type in by Name.

<# Gather variables #>
$siteColl = read-host "What is the target site collection?";
$fieldToAdd = read-host "Which site column should be added the content types in contentTypes.txt?";

<# Import from external CSV file #>
$CTList = Import-Csv contentTypes.txt

ForEach ($item in $CTList){
$TargetCT = $($item.TargetCT)
$web = Get-SPWeb $siteColl
$ct = $web.ContentTypes[$TargetCT]

<# Get link to the columnn from web #>
$spColumn = New-Object Microsoft.SharePoint.SPFieldLink ($web.Fields[$fieldToAdd])

<# Add the column to the content type #>
$ct.FieldLinks.Add($spColumn)
$ct.Update()
}
<# Dispose #>
$web.Dispose()


Jeff

No comments:

Post a Comment