Skip to content

Instantly share code, notes, and snippets.

@asadrefai
Last active August 29, 2015 14:19
Show Gist options
  • Save asadrefai/7a22c002959cf233f8e5 to your computer and use it in GitHub Desktop.
Save asadrefai/7a22c002959cf233f8e5 to your computer and use it in GitHub Desktop.
Reorder content types in SharePoint list csom PowerShell
#Load SharePoint client assemblies
#
Try{
Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'
Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll'
Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll'
}
catch {
Throw "Unable to load SharePoint Client runtime"
}
function Reorder-ContentTypesInList()
{
param(
[Parameter(Mandatory=$true)][string]$url,
[Parameter(Mandatory=$true)][System.Net.NetworkCredential]$credentials,
[Parameter(Mandatory=$true)][string]$listName,
[Parameter(Mandatory=$true)][string[]]$ContentTypeNamesInOrder
)
begin{
try
{
#get Client Object
#
$context = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$context.Credentials = $credentials
#Retrieve List
#
$list = $context.Web.Lists.GetByTitle($listName)
$context.Load($list)
$context.ExecuteQuery()
#Get Content Types from a list
#
$contentTypes = $list.ContentTypes
$context.Load($contentTypes)
$context.ExecuteQuery()
}
catch{
Write-Host "Error while getting context. Error -->> " + $_.Exception.Message -ForegroundColor Red
}
}
process{
try
{
#Making generic list of content type ids in passed order
#
$ctList = New-Object System.Collections.Generic.List[Microsoft.SharePoint.Client.ContentTypeId]
Foreach($ct in $ContentTypeNamesInOrder){
$ctToInclude = $contentTypes | Where {$_.Name -eq $ct}
$ctList.Add($ctToInclude.Id)
}
#Updating content type order
#
$list.RootFolder.UniqueContentTypeOrder = $ctList
$list.Update()
$context.Load($list)
$context.ExecuteQuery()
Write-Host "Content Types Reordered successfully" -ForegroundColor Green
}
catch
{
Write-Host ("Error while reordering content types in a list. Error -->> " + $_.Exception.Message) -ForegroundColor Red
}
}
end{
$context.Dispose()
}
}
$credentials = Get-Credential
$ContentTypesInOrder = "Content Type 1", "Content Type 2", "Content Type 3"
Reorder-ContentTypesInList 'http://YourSite' $credentials 'Your List Name' $ContentTypesInOrder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment