Automating SharePoint Online Tasks (O365) using PowerShell + CSOM – Part 4

This is my fourth ​blog post in the Automating SharePoint Online using PowerShell + CSOM Series. Here are the list of old posts in this series.

Automating SharePoint Online Tasks (O365) using PowerShell + CSOM – Part 1​

Automating SharePoint Online Tasks (O365) using PowerShell + CSOM – Part 2​

Automating SharePoint Online Tasks (O365) using PowerShell + CSOM – Part 3

Just to reiterate, what we want to achieve is to create site columns and content types and then adding site columns to content type and then finally adding content type to list.

So in this blog post I am going to show you how to add site columns to Content Type using PowerShell and CSOM.

 

# ......START Authenticate....................
    .\1_Authenticate.ps1
    #........END Authenticate.....................
    #........START - Get content type........................

    $web = $ctx.Web
    $contentTypes = $web.ContentTypes;
    $ctx.Load($web)
    $ctx.Load($contentTypes);
    $ctx.ExecuteQuery()
    #........END - Get Content type...............​

# Get the Content Type using ID.
$spsCT = $contentTypes.GetById("0x01010073F185B2CDDFDF4BB02CBE44FE14DAE3");
        $ctx.Load($spsCT);
        $ctx.ExecuteQuery();

        $spsFields = $web.Fields;
        $field = $spsFields.GetByInternalNameOrTitle("SessionTitle");
        $ctx.Load($spsFields);
        $ctx.Load($field);
        $ctx.ExecuteQuery();

        #FieldLinks represents the collection of column or field references in a content type.

        $fieldRefCollection = $spsCT.FieldLinks;
        $ctx.Load($fieldRefCollection);
        $ctx.ExecuteQuery();

        #TODO : If Condition to check if the field already exists

        $fieldReferenceLink = New-Object Microsoft.SharePoint.Client.FieldLinkCreationInformation


        $fieldReferenceLink.Field = $field;
        $spsCT.FieldLinks.Add($fieldReferenceLink);
        $spsCT.Update($true);
        $ctx.ExecuteQuery();

That would get you your content type with the site columns added.