Blogger

  • This email address is being protected from spambots. You need JavaScript enabled to view it.

    Recent items

Login

Thursday, 05 July 2012 08:26

Delete field and all its references

Written by
Rate this item
(0 votes)

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

View source
 
 
 
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'

Read 10411 times Last modified on Tuesday, 12 January 2016 10:44

2 comments

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.