Wednesday, March 27, 2013

Delete a Field(Column) in SharePoint List using PowerShell

Hello People,
The following is a code snippet from PowerShell to completely remove or delete a field in a SharePoint list. The code uses the GUID to find the field (column). I tested this with SharePoint 2010. Feel free to modify the code. :)

#Source Help - http://dotnetfollower.com/wordpress/2012/07/sharepoint-how-to-delete-a-list-fieldcolumn-programmatically/

$web=Get-SPWeb "http://mySite/"
$list=$web.Lists.TryGetList("My List Name")
if ($list -ne $null) {
    foreach($column in $list.Fields){
        if ($column.Id -eq "[GUID]") {
            write-host -f green "Deleting column with Internal name as : " $column.InternalName
            
            if ($column.ReadOnlyField)
            {
                $column.ReadOnlyField = $false;
                $column.Update()
            }

            if ($column.Hidden)
            {
                $column.Hidden = $false;
                $column.Update()
            }
     
            if ($column.AllowDeletion -eq $null -or !$column.AllowDeletion.Value)
            {
                $column.AllowDeletion = $true
                $column.Update()
            }
     
            $column.Delete()
            $column.ParentList.Update()

        }
    }
}
else
{
    write-host "list is null"
}

No comments:

Post a Comment