Managing Content Types for a list with Powershell

…this post was published on 2015 September 24.

First i created a new content type – this time using GUI. The name for this new content type ( Type Item ) it is: Custom_Content1

It is a minimal item ( with default mandatory column Title ) and a custom site column, single line text: AUTO

Step 1. How to add this new content type to $mylist.

The code for that is this one:

#define a variable for your content type which you will need to ad to your list

$mycontenttype = $mysite.ContentTypes | Where-Object {$_.Name -eq “Custom_Content1”}

# first check if your site permit new content type

$mylist.ContentTypesEnabled=$true

$mylist.update()

# add this new content type to your list

$mylist.ContentTypes.Add($mycontenttype)

$mylist.Update()

#Verify which content types are attahced to your list

$mylist.ContentTypes.name

 

Step 2. Change the default content type for your list

$currentOrder = $mylist.ContentTypes

$result=New-Object System.Collections.Generic.List[Microsoft.SharePoint.SPContentType]

$mydefaultcontent = $currentOrder | Where-Object {$_.Name -eq “Custom_content1”}

$result.Add($mydefaultcontent)

foreach ($ct in $currentOrder){

if ($ct.Name.Contains(!“Custom_Content1”)) {

$result.Add($ct)

}

}

$mylist.RootFolder.UniqueContentTypeOrder = $result

$mylist.RootFolder.Update()

 

Step 3. Verify the list’s content types order

a. using GUI

b. using CLI

reinialise $mylist and next

$mylist.ContentType.Name

Step 4. Adding one by one items in the list

$new_item = $mylist.Items.add()

$new_item[“Title”]=“masina”

$new_item[“AUTO”]=“DACIA”

$new_item.Update()

 

Step 4. Adding multiple items imported from csv file

First you should have  a .csv file like this

and the code for this:

$mysource = Import-Csv auto.csv

foreach ($line in $mysource)

{

$line.title

$line.AUTO

$new_item = $mylist.Items.add()

$new_item[“Title”]=$line.title

$new_item[“AUTO”]=$line.AUTO

$new_item.Update()

}

This entry was posted in csv, Powershell, Sharepoint 2013. Bookmark the permalink.