Add Fields to List using CSOM and PowerShell


A very basic script to add site columns to SharePoint Online List using Client Side Object Model and PowerShell.  This is a starter script and can be upgraded to allow support for content types as well. 

#$Creds = Get-Credential -Message “Please enter SPO Admin Credentials.”
$SPOSiteURL = https://tenant.sharepoint.com/
#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\16\ISAPI\Microsoft.SharePoint.Client.dll” -ErrorAction Stop
Add-Type -Path “C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll” -ErrorAction Stop

$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Creds.UserName, $Creds.Password)
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SPOSiteURL)
$ctx.Credentials = $credentials
$ctx.Load($ctx.Web);
Write-Host “Please enter Library Title” -ForegroundColor Yellow
$LibraryName = Read-Host
$List = $ctx.web.Lists.GetByTitle($LibraryName)
$ctx.Load($List);
$ctx.ExecuteQuery()

if($List -eq $null)
{
  return;
}

$Fields = $ctx.web.AvailableFields
$ctx.Load($Fields)
$ctx.ExecuteQuery()

$CustomerRepType = $ctx.Web.AvailableFields | Where {$_.Title -eq “CustomerRepType”}
$DocumentType = $ctx.Web.AvailableFields | Where {$_.Title -eq “DocumentType”}
$ctx.Load($CustomerRepType)
$ctx.Load($DocumentType)

$LegalDocumentTypes = $ctx.Web.AvailableFields | Where {$_.Title -eq “LegalDocumentType”}
$Product = $ctx.Web.AvailableFields | Where {$_.Title -eq “Product”}
$ctx.Load($LegalDocumentTypes)
$ctx.Load($Product)

$Solution = $ctx.Web.AvailableFields | Where {$_.Title -eq “Solution”}
$WWRegion = $ctx.Web.AvailableFields | Where {$_.Title -eq “WWRegion”}
$ctx.Load($Solution)
$ctx.Load($WWRegion)
$ctx.ExecuteQuery()

#Add fields to the list
$List.Fields.Add($CustomerRepType)
$List.Fields.Add($DocumentType)
$List.Fields.Add($LegalDocumentTypes)
$List.Fields.Add($Product)
$List.Fields.Add($Solution)
$List.Fields.Add($WWRegion)
$List.Update()
$ctx.ExecuteQuery()

#Add fields to the default view
$DefaultView = $List.DefaultView
$DefaultView.ViewFields.Add(“CustomerRepType”)
$DefaultView.ViewFields.Add(“DocumentType”)
$DefaultView.ViewFields.Add(“LegalDocumentTypes”)
$DefaultView.ViewFields.Add(“Product”)
$DefaultView.ViewFields.Add(“Solution”)
$DefaultView.ViewFields.Add(“WWRegion”)
$DefaultView.Update()
$ctx.ExecuteQuery()

Script is also available

https://gallery.technet.microsoft.com/Add-Colums-to-List-CSOM-ee62a96a