Delete field and all its references
A simple way to delete a Field from all content types, lists and clean all its references, is to run this script (the attachment is at the end of the article):
Show/Hidden bash code
param([string]$serverUrl = $(Throw "You have to specify the serverUrl"),[string]$fieldName = $(Throw "You have to specify the InternalName field to be delete"))
# Load SharePoint PowerShell
$snapin = get-pssnapin | `
where { $_.Name -eq “Microsoft.SharePoint.PowerShell” }
if($snapin -eq $null) {
Add-PsSnapin Microsoft.SharePoint.PowerShell
}
#—————————————————————————-
# Delete Field
#—————————————————————————-
Write-Output “Start removing field:” $fieldName
$site = Get-SPSite $serverUrl
$web = $site.RootWeb
#Delete field from all content types
foreach($ct in $web.ContentTypes) {
$fieldInUse = $ct.FieldLinks | Where {$_.Name -eq $fieldName }
if($fieldInUse) {
Write-Output “Remove field from CType:” $ct.Name
$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-Output “Delete column from ” $list.Title ” list on:” $_.URL
#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-Output “Remove field:” $fieldName
$field=$web.Fields.GetFieldByInternalName($fieldName)
$field.AllowDeletion = $TRUE
$field.Sealed=$FALSE
$field.Update()
$web.Fields.Delete($fieldName)
}
$web.Dispose()
$site.Dispose()
To run the script, open powershell and write this command from the same script folder:
DeleteFieldAndAllReferences.ps1 -serverUrl http://www.yoursite.com -fieldName 'InternalFieldNameToBeDeleted'