Last active
April 26, 2021 11:20
-
-
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..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
} |
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.
I'm having the smae problem as Frederik.
Your suggestions throws back an 403 Forbidden error.
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
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.