Showing posts with label ContentType. Show all posts
Showing posts with label ContentType. Show all posts

Wednesday, August 14, 2013

Create Content Types and Fields using Powershell

 Below script will work for

1.       1. Add Content Types to the web site
a.       Create a Content Type
b.      Add fields to Content Type
c.       Modify existing fields of  Content Type
d.      Delete fields from Content Type
e.      Create a new field and then add to the content type
2.       2. Add Content Type to the SharePoint List
3.       3. Sorting Content Types in the List

I referred below posts



Start-SPAssignment -Global

function  Sort-ContentTypes(
       [Microsoft.SharePoint.SPList]$list) {

         Write-Host $list.Title
$rootFolder = $list.RootFolder
$DefaultContentTypeName = "Document"  #setting "Document" as default content type.

 $rootFolder.UniqueContentTypeOrder = $null
 $rootFolder.Update()

#Get content types fromt the button
$contentTypesInPlace = New-Object 'System.Collections.Generic.List[Microsoft.SharePoint.SPContentType]'
$contentTypesInPlace = $rootFolder.ContentTypeOrder
 
#Has a default content type name been specified?
      if ($DefaultContentTypeName)
      {
            $contentType = $contentTypesInPlace | where { $_.Name -eq $DefaultContentTypeName }
            if ($contentType -ne $null)
            {
                  #Add the default content type
                  $sortedListOfContentTypes = New-Object 'System.Collections.Generic.List[Microsoft.SharePoint.SPContentType]'
                  $sortedListOfContentTypes += $list.ContentTypes[$DefaultContentTypeName]
                   
                  #Remove the default content type from the list
                  $contentTypesInPlace = $contentTypesInPlace | where {$_.Name -ne $DefaultContentTypeName}
            }
            else
            {
                  Write-Error "$DefaultContentTypeName was not found in the list, sorting by Name alone"
            }
      }
      else
      {
            Write-host "No default content type specified"
      }
       
      #sort the remaining content types and add the sorted list
      foreach ($contentType in $($contentTypesInPlace | Sort-Object -Property Name ))
      {
      #Add the content types
            $sortedListOfContentTypes = [Microsoft.SharePoint.SPContentType[]] $sortedListOfContentTypes + $contentType
      }

      $rootFolder.UniqueContentTypeOrder = [Microsoft.SharePoint.SPContentType[]] $sortedListOfContentTypes
       
      #Update the root folder
      $rootFolder.Update()
      Write-host "ContentType(s) sorted and added to the dropdownlist in list $($list.Name)"
     
 }



$url = "http://spdev5:8002/sites/library"
$web = get-spweb $url

#The Display Name of the Content Type
$ctypeName = "SuryaCT1"

try{

if($web.availablecontenttypes[$ctypeName] -eq $null)
{
      $ctypeParent = $web.availablecontenttypes["Document"]
      $ctypeTest = new-object Microsoft.SharePoint.SPContentType($ctypeParent, $web.contenttypes, $ctypeName)
      ##group name
      $ctypeTest.Group = "Custom Group"
      $web.contenttypes.add($ctypeTest)
     
#     $ctypeTest = $web.ContentTypes[$ctypeName]
     
      Write-Host "ctypeAgenda" $ctypeTest.id
     
      ##Add fields to the ContentType

      $field = $web.fields.getfield("Field1")
     
      if($ctypeTest.Fields["Field1"] -eq $null)
      {
            $fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
            $ctypeTest.fieldlinks.add($fieldLink)
      }
     
      ##Update existing fields - as Required
      if($ctypeTest.Fields["Field2"] -ne $null)
      {
            $field = $ctypeTest.Fields["Field2"]
            $ctypeTest.FieldLinks[$field.Id].Required=$true
      }
       
     
      ##Delete fields from  ContentType
           
      if($ctypeTest.Fields["Field3"] -ne $null)
      {
         Write-Host "Field2"
        $field = $ctypeTest.Fields["Field3"]
        $fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
        $ctypeTest.FieldLinks.Delete($fieldLink.id);
      }
     
      ##create new field and then add to the ContentType
       
      $web.fields.add("SuryaField", "Text", $false)
      $field = $web.fields.getfield("SuryaField")
      $field.Group = "Custom Columns"
      $fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
      $ctypeTest.fieldlinks.add($fieldLink)


      $ctypeTest.Update($true)
       
}
else
{
      Write-Host $ctypeTest " Contentype is already avilable in the site."
}

#$ctypeTest = $web.ContentTypes[$ctypeName]
## Add ContentType to the SharePoint List
      if($ctypeTest -ne $null)
            {
           
            $list =  $web.Lists.TryGetList("suryadocs")
           
            if($list.ContentTypesEnabled -eq $false   )
            {
            $list.ContentTypesEnabled = $true;
                  $list.Update()
            }
             
              if ($list.ContentTypes[$ctypeTest.Name] -eq $null)
             {
               $list.ContentTypes.Add($ctypeTest);
                   Write-Host $ctypeTest.name " ContentType added"
                   Sort-ContentTypes $list
             }
            }
}
catch
{
      Write-Host "Error occurred while Updating:"  $_  -ForegroundColor Red
}

Stop-SPAssignment –Global



Wednesday, July 3, 2013

Add Field or Column to ContentType and set the column order



When you run below script it will add a field to content type and set the order. For my field I want to set the order next to ‘SAC Doc’ filed. For that I am reading existing index of ‘SAC Doc’ field and setting to my new field.

For column order you can refer this post as well

  http://sharepointempower.com/2013/03/column-ordering-in-sharepoint-2010/

It will create a log file in your location where you are running your script

function SetColumnOrder([Microsoft.SharePoint.SPContentType]$contentType)
 {
            #Write-Host $contentType.name
            [Microsoft.SharePoint.SPFieldLinkCollection]$flinks = $contentType.FieldLinks;
               #array object
               $fieldsArray = New-Object 'System.Collections.Generic.List[string]';

          #Read all the InternalNames of the FieldLinks into a list
          foreach($fieldLink in $flinks){
               $fieldsArray.Add($contentType.Fields[$fieldLink.ID].InternalName);
          }
     
              $fieldchkboxInternalName =$contentType.Fields["SAC DOC"].InternalName
             # Write-Host $fieldchkboxInternalName
              $fieldDDLInternalName =$contentType.Fields["ddlTest"].InternalName
             
          if($fieldsArray.Contains($fieldchkboxInternalName)){

              $indexChkbox = $fieldsArray.IndexOf($fieldchkboxInternalName)
                    #Write-Host "checkbox index:" $indexChkbox
                   
                    $indexDDL = $fieldsArray.IndexOf($fieldDDLInternalName)
                     #Write-Host "ddlindex:"  $indexDDL
                     #Write-Host  "fieldsArraycount" $fieldsArray.Count
                   
                    if($indexChkbox -ne $indexDDL )
                {
                          $fieldsArray.RemoveAt($indexDDL)
                         
                          if($indexChkbox -le $fieldsArray.Count -1){
                           $fieldsArray.Insert($indexChkbox,$fieldDDLInternalName)
                                     Write-Host "SAC ddl index:"  $fieldsArray.IndexOf($fieldDDLInternalName)
                                     $msg = ("{0},{1}" -f "SAC ddl index order :", $fieldsArray.IndexOf($fieldDDLInternalName))
                                    $msg | out-file -FilePath $logfile  -append
                          }
                       #else{
                        #  $fieldsArray.Add($fieldDDLInternalName);
                        #}
                        }
             #Add the array to the reorder
             $flinks.Reorder($fieldsArray.ToArray());
             #Update the ContentYpe
             $contentType.Update($true)

            }
                             
}


$URL = "http://spdev5:8002/sites/library"
$site = New-Object Microsoft.SharePoint.SPSite($URL)
$web = $site.openweb("")


#logging
$timestamp = get-date -format "yyyyMMdd_hhmmtt"
$filenameStart = "SAC_AddField2ContentTypes"
$logfile = ("{0}{1}.csv" -f $filenamestart, $timestamp)

$header = "S.No,Message"
$header | out-file -FilePath $logfile



$fieldName = "ddlTest"
$field = $web.Fields[$fieldName]
#$ct = $web.ContentTypes[$contentTypeName]
Write-Host "Fieldname:" $field
$index=40
$ContentTypes = $web.ContentTypes

 try{

      foreach ($ContentType in $ContentTypes)
      {
          $contentTypeGroup = $ContentType.Group
          $contentTypeName = $ContentType.Name

          if ( $contentTypeGroup  -like '*DMID*')
          {
              
                   #if($ContentType.Fields["SAC DOC"] -ne $null)
                   #{
                    #  write-host $ContentType.Name #$MyField.Id
                        #$MyField=$ContentType.Fields["SAC DOC"]
                      #$ContentType.FieldLinks[$MyField.Id].Required=$true
                  # }
                 
                  #if($ContentType.Name -eq  "Laboratory Normal Ranges")
                  if($ContentType.Name -eq "CI"  -or $ContentType.Name -eq "Lab" )
                  {    
                        if($ContentType.Fields["ddlTest"] -eq $null)
                        {
                              $link = new-object Microsoft.SharePoint.SPFieldLink $field
                              $ContentType.FieldLinks.Add($link)
                              $ContentType.Update($true)
                              write-host "'SAC Doc' dropdownlist added to: " $ContentType.Name
                              $msg = ("{0},{1}" -f "'SAC Doc' dropdownlist added to:", $ContentType.Name)
                              $msg | out-file -FilePath $logfile  -append
                              SetColumnOrder $ContentType
                              #break;    
                        }
                        else
                        {
                              write-host  "'SAC Doc' dropdownlist already added to: " $ContentType.Name -BackgroundColor Red
                              $msg = ("{0},{1}" -f "'SAC Doc' dropdownlist already added to:", $ContentType.Name)
                              $msg | out-file -FilePath $logfile  -append
                        }
                       
                  }
                 
          }
       }
 }
 catch [System.Management.Automation.ExtendedTypeSystemException]
 {
    Write-Host $_.Exception.ToString()
       $msg = ( "{0},{1}" -f "Error occurred while reading list..:", $_)
       $msg | out-file -FilePath $logfile  -append
 }

$web.Dispose()
$site.Dispose()




Followers