Client Side Object Model Basics

When I went to port over my existing SharePoint PowerShell scripts to use SPO, I found that I needed to rewrite them all since I couldn’t just use some remote PS session any longer which is what I had been doing. After I got it all working, it’s quite nice actually. I am putting notes together to help me remember how to do it, and in case anyone may find this useful also…


  • You’ll need to have the SharePoint Online Client Components SDK installed. Get this from here:
  • You’ll need to have an existing SharePoint Online instance to access. For example, I have one setup and already have site collection admin rights setup for myself and workspace owner rights setup for my service account.
  • You’ll need a workstation or server to install that SDK on and to run any scheduled tasks that run your PS scripts. I use a server to run all of my tasks that do stuff, so it keeps things going on its own.

Creating a connection:

I like to keep some repeatedly needed pieces of information in a handful of global variables. Also, I don’t like to manually enter credentials every time I go to connect to SPO so I store mine and access it as shown below…

# store the URL and credentials to make the connection with...
$spoSpWeb = ''
$spoUser = ''
$spoCredFile = '\\greglabserver1\private\cred\spoCred.txt'
# one-time task: run these 2 lines only if you haven't stored your credential yet...
# $secureCred = Read-Host -AsSecureString "Enter your service account's password..."
# $secureCred | ConvertFrom-SecureString | Out-File -FilePath "$spoCredFile"
$spoCred = Get-Content -Path "$spoCredFile" | ConvertTo-SecureString

# load the CSOM client files...
# connect to your site...
If (!($Context.Url -eq $spoSpWeb)) {
  $Context = New-Object Microsoft.SharePoint.Client.ClientContext($spoSpWeb)
  $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($spoUser,$spoCred)
  $Context.Credentials = $Creds

At this point you should then be connected and can start doing lots of things. I’ll put some examples once I get them cleaned up, then they will be listed here as child pages…