Skip to content

Instantly share code, notes, and snippets.

@chrisobriensp
Last active April 26, 2021 11:20
Show Gist options
  • Save chrisobriensp/7684961 to your computer and use it in GitHub Desktop.
Save chrisobriensp/7684961 to your computer and use it in GitHub Desktop.
PowerShell and CSOM to authenticate to Office 365 and get a ClientContext object..
# replace these details (also consider using Get-Credential to enter password securely as script runs)..
$username = "[email protected]"
$password = "SomePassword"
$url = "https://SomeSite.sharepoint.com"
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
# the path here may need to change if you used e.g. C:\Lib..
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"
# note that you might need some other references (depending on what your script does) for example:
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"
# connect/authenticate to SharePoint Online and get ClientContext object..
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$clientContext.Credentials = $credentials
if (!$clientContext.ServerObjectIsNull.Value)
{
Write-Host "Connected to SharePoint Online site: '$Url'" -ForegroundColor Green
}
@Frederik80
Copy link

Is it possible to log in with CSOM without password, like with pnponline using '-weblogin'? We have MFA with password and only a digital key.

I used the code above but it won't work anymore because it won't accept UN/PWD.

@nefariousOne
Copy link

You'd have to be a Tenant admin and use this:

Connect-SPOService -Url https://{tenant}-admin.sharepoint.com
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($Url)

You will then have access to all Site Collections available within your tenant and itterate through them to find the Site Collection you'd like to work with.

@simb55
Copy link

simb55 commented Jan 7, 2020

I'm having the smae problem as Frederik.
Your suggestions throws back an 403 Forbidden error.

@Smartis2812
Copy link

Smartis2812 commented Feb 28, 2020

The line if (!$clientContext.ServerObjectIsNull.Value) is useless because it will always return true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment