Skip to content

Instantly share code, notes, and snippets.

@IAMPetro
Created December 11, 2016 09:52
Show Gist options
  • Save IAMPetro/d6d6f827df0c5143e0f0bd6339fc34a4 to your computer and use it in GitHub Desktop.
Save IAMPetro/d6d6f827df0c5143e0f0bd6339fc34a4 to your computer and use it in GitHub Desktop.
SharePoint: Add Content Type Fields
function Add-SPContentTypeField
{
<#
.Synopsis
This function will allow you to add a library field to a Content Type
.Description
This function will add the nominated site column/ library column to a nominated Content Type
within all of the 'Document Libraries' in the given Site Collection
.Example
C:\> Add-SPContentTypeField –SiteUrl “http://yourdomain.com/sites/Finance –FieldName "myField" -CTypeAddedTo "myContentType"
.Notes
Name: Add-SPContentTypeField
Author: Petro Margaritis
Last Edit: 19/07/2012
Keywords: Fields, Site Columns, Content Types
.Link
http://www.iampetro.com/
#>
Param (
[parameter(Mandatory=$true)][string]$SiteUrl,
[parameter(Mandatory=$true)][string]$FieldName,
[parameter(Mandatory=$true)][string]$CTypeAddedTo
)
$site = Get-SPSite $SiteUrl
# Walk through each site in the site collection
$site | Get-SPWeb -Limit all | ForEach-Object {
write-host "Checking site:"$_.Title -Foregroundcolor Green
# Go through each document library in the site
foreach ($list in $_.Lists | where { $_.BaseTemplate -eq "DocumentLibrary" })
{
# Check to see if the library contains the content type we are looking for
if (($list.ContentTypes | where { $_.Name -eq $CTypeAddedTo }) -eq $null)
{
Write-Host "The Content:" $CTypeAddedTo "does not exist in the library:" $list.Title -Foregroundcolor Red
}
else
{
# Check to see if the library contains the field we are looking for
if (($list.Fields | where { $_.Title -eq $FieldName }) -ne $null)
{
# Get the content type you want to add the field to
$ct = $list.ContentTypes[$CTypeAddedTo]
# Get the column you want to copy
$field = $list.Fields[$FieldName]
# Add the column to the content type
$ct.Fieldlinks.Add($field)
$ct.update()
# Add additional column settings
$ctFieldLinks = $ct.FieldLinks | Where {$_.Name -eq $field.Title}
# OPTIONAL: This will set the column to hidden so that it is not viewable in the edit form
$ctFieldLinks.Hidden = $true
# Set Field to require value
$ctFieldLinks.Required = $true
$ct.Update()
Write-Host "The Field:" $field.Title "has been successfully added to the library:" $list.Title -Foregroundcolor Cyan
}
else
{
Write-Host "The Field:" $FieldName "does not exist in the library:" $list.Title -Foregroundcolor Yellow
}
}
}
}
# Dispose of the site object
$site.Dispose()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment