Pages

Showing posts with label Poweshell. Show all posts
Showing posts with label Poweshell. Show all posts

Wednesday, April 25, 2012

Removing Columns for Content Types

Creating a new custom content type? Have to inherit from something but you don't want to include all the fields/columns from the parent?

Simple (in most cases). Use the following powershell script to remove (note does not delete the column which doesn't belong to you to delete anyway :))

$ver = $host | select version
if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"}
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

#Attach to the web and content type
$web = Get-SPWeb http://intranet.contoso.com/
$ct = $web.ContentTypes["Content Type"]

#Insert name of column to remove from Content Type
$columnName = "Comments"

#Get link to the columnn from the web
$spFieldLink = $ct.FieldLinks[$columnName]
#Recently I tried to use this script and this line failed, I replaced it with the one above and its fine.
#$spFieldLink = New-Object Microsoft.SharePoint.SPFieldLink($web.Fields[$columnName])

#Remove the column from the content type and update
$ct.FieldLinks.Delete($spFieldLink.Id)
$ct.Update()

#Test that the column was successfully removed from the Content Type
if ($ct.Fields[$columnName])
{
    Write-Host "$columnName was not removed"
}
else
{
    Write-Host "$columnName was removed"
}

Note: Only issue I have found so far is that I still cannot remove all fields that I want removed. In my case I wanted to remove the "Comments" field from a content type but for some reason it won't remove.

EDIT: Figured out how to delete/remove the Comments field from my content type.
First make it hidden (you can do this through the UI or in a script) then the above script can be used to remove it. Weird by it works