Thursday, April 7, 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 :)