Friday, April 8, 2011

Powershell Script to Delete Site Columns from SharePoint SiteCollection RootWeb


The code below accepts Site Collection URL and Site Columns List as configurable parameters, it then goes through each semi-colon separated Site Columns List and deletes it from the RootWeb of the Site Collection.

Instructions:
1. Copy and Paste the code below and save it as DeleteSiteColumns.ps1, see highlighted sections to change configurable values:

Add-PsSnapin Microsoft.SharePoint.PowerShell
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

set-variable -option constant -name url  -value "http://localhost/" # Specify your Site collection URL
$siteColumnsList = "Display Name Column1;Display Name Column2;Display Name Column3" # Specify a list of Site Column Names to be deleted

$site = new-object Microsoft.SharePoint.SPSite($url)
$array = $siteColumnsList.Split(";")

foreach($colms in $array)
{
try
{
$column = $site.rootweb.Fields[$colms]
$site.rootweb.Fields.Delete($column)
Write-Host $column.Title "deleted successfully."
}
catch [System.Exception]
{
Write-Host $column.Title "deleted failed."
#Best Attempt to Remove Site Columns
}
}

$site.Dispose()

Remove-PsSnapin Microsoft.SharePoint.PowerShell
Echo Finish

2. To automatically run the .ps1 script as a batch utility, Copy and paste code below and save it with a .bat file extension


cd /d %~dp0
powershell -noexit -file ".\DeleteSiteColumns.ps1" "%CD%"
pause


Run the Script and Enjoy :)

4 comments:

  1. Hello!
    Nice script! However, I think that it won't delete a Column that is used in any Content Type.
    Are there any script to delete a Column from all Content Types?

    Best regards!

    ReplyDelete
  2. Yes script to delete from Content Types would be AWESOME!

    ReplyDelete
  3. I am not able to delete a Managed Metadata type site column using this (or any other) code. Any suggestions?

    ReplyDelete
  4. Thank you so much!!!

    ReplyDelete