Created
October 9, 2017 17:38
-
-
Save joerodgers/ae8723b0f5c49d8a0bbd92284cb0c0fd to your computer and use it in GitHub Desktop.
Allow SPO CSOM and Microsoft.SharePoint.PowerShell PSSnapIn to Coexist in the same AppDomain
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
Add-PSSnapin -Name Microsoft.SharePoint.PowerShell | |
# prevent issues with the SharePoint API certificate validation procedures (must be after loading sharepoint snapin) | |
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} | |
function Add-FormsAuthRequestHeader | |
{ | |
param | |
( | |
[Parameter(Mandatory=$true)][Object]$ClientContext | |
) | |
begin | |
{ | |
# try to dynamically locate the the CSOM assemblies | |
$referencedAssemblies = $([AppDomain]::CurrentDomain.GetAssemblies() | ? { -not $_.GlobalAssemblyCache -and $_.FullName -match "Microsoft.SharePoint.Client." }).Location | |
} | |
process | |
{ | |
Add-Type -ReferencedAssemblies $referencedAssemblies -TypeDefinition @" | |
using System; | |
using Microsoft.SharePoint.Client; | |
namespace WebRequestExecutor | |
{ | |
public static class AuthHeaderHelper | |
{ | |
public static void AddAuthHeader(ClientContext context) | |
{ | |
context.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(AddAuthHeader); | |
} | |
private static void AddAuthHeader(object sender, WebRequestEventArgs e) | |
{ | |
e.WebRequestExecutor.RequestHeaders.Remove("X-FORMS_BASED_AUTH_ACCEPTED"); | |
e.WebRequestExecutor.RequestHeaders.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f"); | |
} | |
} | |
} | |
"@ | |
[WebRequestExecutor.AuthHeaderHelper]::AddAuthHeader($ClientContext); | |
} | |
end | |
{ | |
} | |
} | |
Add-Type -Path "E:\Microsoft.SharePointOnline.CSOM.16.1.6008.1200\lib\net45\Microsoft.SharePoint.Client.dll" | |
Add-Type -Path "E:\Microsoft.SharePointOnline.CSOM.16.1.6008.1200\lib\net45\Microsoft.SharePoint.Client.Runtime.dll" | |
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext( "https://contoso.sharepoint.com/sites/teamsite" ) | |
$clientContext.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials( "admin@contoso.onmicrosoft.com", $(ConvertTo-SecureString -String "pass@word1" -AsPlainText -Force )) | |
Add-FormsAuthRequestHeader -ClientContext $clientContext | |
$clientContext.ExecuteQuery() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment