Office 365 - PowerShell Script to Create a List, Add Fields and Change the Default View all using CSOM

I'm my continued quest to get to grips with the Client Side Object Model (CSOM) in SharePoint 2013, I have put together a sample script below that connects to a Site Collection within an O365 tenant and does the following:

  • Creates a list using the "Custom" list template
  • Adds two Site Columns to the list (City and Company)
  • Adds these fields to the default view
  • Adds an item to the list

You may find this useful as a reference! The usual disclaimers apply :)

All you need to run this script is an O365 tenant, the SharePoint client components SDK installed on the machine running the script - and to update the $User, $SiteURL and $ListTitle variables. When the script is executed it will prompt for the password of the user specific in the $User variable.

#Specify tenant admin and site URL
$User = ""
$SiteURL =
$ListTitle = "List Title"

#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
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"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)

#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

#Retrieve lists
$Lists = $Context.Web.Lists

#Create list with "custom" list template
$ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListInfo.Title = $ListTitle
$ListInfo.TemplateType = "100"
$List = $Context.Web.Lists.Add($ListInfo)
$List.Description = $ListTitle

#Retrieve site columns (fields)
$SiteColumns = $Context.Web.AvailableFields

#Grab city and company fields
$City = $Context.Web.AvailableFields | Where {$_.Title -eq "City"}
$Company = $Context.Web.AvailableFields | Where {$_.Title -eq "Company"}

#Add fields to the list

#Add fields to the default view
$DefaultView = $List.DefaultView

#Adds an item to the list
$ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$Item = $List.AddItem($ListItemInfo)
$Item["Title"] = "New Item"
$Item["Company"] = "Contoso"
$Item["WorkCity"] = "London"

Brendan Griffin