Wednesday, July 4, 2012

Delete site column through PowerShell script


This script only me one hour.  But I think it's worth to share it out.

What it does is:

  • Delete relevant column instances from lists;
Need to change "AllowDeletion" and "ReadOnlyField" attribute first.
  • Delete relevant column references from content types;
  • Delete site column



-----------------------------------------------------------------------
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue"

$SiteUrl = "http://SharePointServer/sites/site1"

function ListSiteColumnUsage([string]$SiteColumnName)
{
$site = Get-SPSite $SiteUrl
$column = $site.RootWeb.AvailableFields[$SiteColumnName]
$column.ListsFieldUsedIn() | ForEach-Object {
$SubWeb = $site.AllWebs[$_.WebID]
$list = $SubWeb.Lists[$_.ListID]

Write-Host "Web:" $SubWeb.Title "List:" $list.Title "ListUrl:" $list.RootFolder.Url "ColumnName:" $column.Name "ColumnID:" $column.ID
}
}

function DeleteSiteColumn([string]$SiteColumnName)
{
$site = Get-SPSite $SiteUrl
$column = $site.RootWeb.AvailableFields[$SiteColumnName]

$column.ListsFieldUsedIn() | ForEach-Object {
$SubWeb = $site.AllWebs[$_.WebID]
$list = $SubWeb.Lists[$_.ListID]

Write-Host "Web:" $SubWeb.Title "List:" $list.Title "ListUrl:" $list.RootFolder.Url

$field = $list.Fields[$SiteColumnName]
$field.AllowDeletion = $TRUE
$field.ReadOnlyField = $FALSE
$field.Update()
$list.Fields.Delete($SiteColumnName)

$SubWeb.Dispose()
}

foreach ($SubWeb in $site.AllWebs)
{
foreach ($ct in $SubWeb.ContentTypes)
{
if (($ct.Sealed -eq $false) -and ($ct.ReadOnly -eq $false))
{
$spFieldLink = New-Object Microsoft.SharePoint.SPFieldLink ($SubWeb.AvailableFields[$SiteColumnName])
if ($spFieldLink -ne $null)
{
$ct.FieldLinks.Delete($spFieldLink.Id)
$ct.Update()
}
}
}
$SubWeb.Fields.Delete($SiteColumnName)
}

$site.Dispose()
}

ListSiteColumnUsage("SiteColumn1")

DeleteSiteColumn("SiteColumn1")

rm function:/ListSiteColumnUsage
rm function:/DeleteSiteColumn
Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

2 comments: