0
votes

I'm trying to add a Content Type to a Document Library within Sharepoint Online. My code below runs with no errors but the Content Type doesn't get added to the Document Library.

Any ideas?

Thanks P

#Bind to site collection  
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

#Get content types of the web
    $Context.Load($Context.Web.ContentTypes)
    $Context.ExecuteQuery()

    #Get the content type by its name
    $ContentType = $Context.Web.ContentTypes | Where {$_.Name -Match $newCT}
    $Context.Load($ContentType)   
    $Context.ExecuteQuery()

    #sharepoint online get content type id
    write-host -f Green "Content Type ID:" $ContentType.Id
    write-host -f Green "Content Type Title:" $ContentType.Name

    $List = $Context.Web.Lists.GetByTitle($DocLibName) 
    Write-host "List is " $DocLibName

    $Context.load($list)
    $Context.load($list.ContentTypes)
    $Context.ExecuteQuery()
    $list.ContentTypesEnabled=$true

    try{
        $addedContentType=$list.ContentTypes.AddExistingContentType($ContentType)
    }catch{
        write-host "ERROR!"
    }

    write-host -f Green "Added content type (" $newCT ") to list (" $DocLibName ")" 

    $list.Update()
``
1
Shouldn't you be doing $addedContentType = $list.ContentTypes.Add($newCT); $list.Update() instead of trying to find an existing contenttype? - Theo
Thanks @Theo I tried that but still the same. The code runs but it doesn't add the content type to the document library. - Pete Whelan
Apologies I am getting an error ... Cannot convert argument "parameters", with value: "Microsoft.SharePoint.Client.ContentType", for "Add" to type "Microsoft.SharePoint.Client.ContentTypeCreationInformation": "Cannot convert th e "Microsoft.SharePoint.Client.ContentType" value of type "Microsoft.SharePoint.Client.ContentType" to type "Microsoft.SharePoint.Client.ContentTypeCreationInformation"." - Pete Whelan
```write-host "List name is " $list.Title write-host "List name is " $list.Id write-host "ContentType is " $ContentType.Name try{ $addedContentType=$list.ContentTypes.Add($ContentType) }catch{ write-host "ERROR!" Write-Host $_ } - Pete Whelan
Never liked Sharepoint.. The thing is, I don't see your code ever calling the .Update() method on the $list. What if you just add that to the code? - Theo

1 Answers

0
votes

Seems I was missing this part ...

        $context.ExecuteQuery()