Tuesday, 22 January 2013

PowerShell – Create/Delete site columns

PowerShell – Create/Delete site columns
#*===========================================================================
#* Purpose: To create/delete site columns of existing Content Type
#*
#*===========================================================================

$url = Read-Host "Enter Site URL?"

Write-Host "Processing.... " -ForegroundColor Yellow

#* Function used to create site column
Function Set-CustomField
{
      param([string] $FieldName,[string] $FieldType,[string] $Description,$web,$contentType,$choices,$Required,$UniqueValues )      
      switch ($FieldType)
    {
        "Text" {$web.fields.add($FieldName, ([Type]“Microsoft.SharePoint.SPFieldType”)::Text, $false)}
        "Choice" {$web.fields.add($FieldName, ([Type]“Microsoft.SharePoint.SPFieldType”)::Choice, $false, $false, $choices)}
        default {$web.fields.add($FieldName, ([Type]“Microsoft.SharePoint.SPFieldType”)::Text, $false)}
    }
      $field = $web.fields.getfield($FieldName)
      $field.Description=$Description
      $field.Required=$Required
      $field.EnforceUniqueValues=$UniqueValues
      #$field.AllowDeletion = $true
      #$field.Sealed = $false

      $fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
      #Add new fields/Site Columns to corresponding content type
      $contentType.fieldlinks.add($fieldLink)

      #Update content type with new fields..
      $contentType.Update()
}

#* Function used to delete site column
Function Remove-CustomField
{
      param([string] $FieldName,$web,$contentType)         
      $field = $web.fields.getfield($FieldName)
      $contentType.fieldlinks.Delete($field.Id)
      $contentType.Update()
}

$site = get-spsite $url
$web = $site.openweb()
$contentType = $web.ContentTypes["NYLIM Records Management"]

#Adding site columns with type as text..
Set-CustomField "Document Type" "Text" "To classify documents." $web $contentType $null $true $false

#Deleting existing site column from corresponding content type..
Remove-CustomField "Document Type" $web $contentType

Write-Host "Process Completed...!!!" -ForegroundColor Yellow
#Dispose objects
$web.Dispose()
$site.Dispose()

Script Execution Steps:-
1)     Enter site URL where the site columns needs to be created/deleted.

No comments:

Post a Comment