PowerShell – Delete field and all references
Posted by Peter Heibrink on December 9, 2011
Sometimes you want to delete a site column from SharePoint and you get the nice message stating “Site columns which are included in content types cannot be deleted. Remove all references to this site column prior to deleting it.”. Really helpful that it states in which ContentTypes the field is used. It gets even worse when the column is also used in lists… You can do this via PowerShell easily:
# Add SharePoint PowerShell Snapin
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {
Add-PSSnapin Microsoft.SharePoint.Powershell
}
#—————————————————————————-
# Delete Field
#—————————————————————————-
function DeleteField([string]$siteUrl, [string]$fieldName) {
Write-Host “Start removing field:” $fieldName -ForegroundColor DarkGreen
$site = Get-SPSite $siteUrl
$web = $site.RootWeb
#Delete field from all content types
foreach($ct in $web.ContentTypes) {
$fieldInUse = $ct.FieldLinks | Where {$_.Name -eq $fieldName }
if($fieldInUse) {
Write-Host “Remove field from CType:” $ct.Name -ForegroundColor DarkGreen
$ct.FieldLinks.Delete($fieldName)
$ct.Update()
}
}
#Delete column from all lists in all sites of a site collection
$site | Get-SPWeb -Limit all | ForEach-Object {
#Specify list which contains the column
$numberOfLists = $_.Lists.Count
for($i=0; $i -lt $_.Lists.Count ; $i++) {
$list = $_.Lists[$i]
#Specify column to be deleted
if($list.Fields.ContainsFieldWithStaticName($fieldName)) {
$fieldInList = $list.Fields.GetFieldByInternalName($fieldName)
if($fieldInList) {
Write-Host “Delete column from ” $list.Title ” list on:” $_.URL -ForegroundColor DarkGreen
#Allow column to be deleted
$fieldInList.AllowDeletion = $true
#Delete the column
$fieldInList.Delete()
#Update the list
$list.Update()
}
}
}
}
# Remove the field itself
if($web.Fields.ContainsFieldWithStaticName($fieldName)) {
Write-Host “Remove field:” $fieldName -ForegroundColor DarkGreen
$web.Fields.Delete($fieldName)
}
$web.Dispose()
$site.Dispose()
}
#Delete the field below
DeleteField http://sharepoint “MyField”