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

This is my second blog post in the Automating SharePoint Online using PowerShell + CSOM Series. In the last article we saw how to authenticate against SharePoint Online site and how to access Web and List using PowerShell + CSOM. Here is the blog post.

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

Just reiterate, we are going to create site columns and content types and then adding site columns to content type and then finally adding content type to list.

So today I am going to show you how to write a code to create a site column using PowerShell and CSOM.

# ……START Authenticate………………..
    .\1_Authenticate.ps1
#……..END Authenticate…………………
 
#……..START – Get Collection of fields ……………………
    $web = $ctx.Web
    $fields = $web.Fields;     
    $ctx.Load($web)    
    $ctx.Load($fields);
    $ctx.ExecuteQuery()
 
#……..END – Get Web collection of fields……………


# Following code if needed if you want to check 
#if the fields you are trying to create already exists or not.
    #foreach ($field in $fields)
    #{
           #Write-Host “”
           #Write-Host $field.InternalName -ForegroundColor Yellow
           #If Condition to check if field already exists
    #}


#KEY-1
    $fieldOption = [Microsoft.SharePoint.Client.AddFieldOptions]::DefaultValue
    $fieldAsXML = “<Field ID='{4F34B2ED-9CFF-4900-B091-4C0033F89945}’ Name=’SessionTitle’ 
DisplayName=’Session Title’ Type=’Text’         
Hidden=’False’ Group=’SPSBoston Site Columns’ 
Description=’SPS Boston Session Title Field’ />”;
 
    $fld = $fields.AddFieldAsXml($fieldAsXML, $true, $fieldOption);
    $ctx.Load($fields);
    $ctx.Load($fld);
    $ctx.ExecuteQuery();
    $fieldAsXML = “<Field ID='{4F34B2ED-8CFF-4900-B091-4C0033F89944}’ Name=’SessionDescription’ 
DisplayName=’Session Description’ Type=’Note’ 
Hidden=’False’ Group=’SPSBoston Site Columns’ 
Description=’SPS Boston Session Description Field’ />”;
 
    $fld = $fields.AddFieldAsXml($fieldAsXML, $true, $fieldOption);
    $ctx.Load($fields);
    $ctx.Load($fld);
    $ctx.ExecuteQuery();
    Write-Host “Done creating Site Column….” -ForegroundColor Green​

The key in the above code is how you access the FieldOption object which is of type enum. Check the code #KEY-1 to see how you can set the enum values.

If you do not know the Enum values then you can simply use the following code to list all values.

[Microsoft.SharePoint.Client.AddFieldOptions].GetEnumValues()

Similarly when creating field if you do not know the different field types then FieldType is also Enum and you can get all available field types as

[Microsoft.SharePoint.Client.FieldType].GetEnumValues()

Rest of the code is self explanatory.

​I hope this helps.