Accessing Mixed-Mode SharePoint Web Applications with CSOM and PowerShell

This post describes how to force Windows Authentication when accessing a SharePoint 2013 Mixed-Mode web application via CSOM from within a PowerShell script.

Overview

I’ve been doing a lot of work with SharePoint Online Dedicated customers lately, and have to use CSOM wrapped in PowerShell to perform a number of site collection maintenance and administrative tasks (if you haven’t used CSOM + PowerShell, you should, and Chris O’Brien’s post is a great place to start). With SPO-D, customers can enable mixed-mode authentication and support partner access via forms auth, however this breaks the traditional method of authenticating using the ClientContext because SharePoint displays the authentication method dialog (windows, or forms). Steve Peschka wrote a great article on how to solve this in C# and in web services, and this post builds on that by providing an implementation for use within PowerShell.

The Challenge

Steve’s post uses an event handler to add an HTTP Header to the request and force Windows Authentication:

 

In PowerShell, normally you add an event handler to a .NET object using the Register-ObjectEvent command, and this was my first attempt at solving this:

However, after modifying the headers collection and tracing in Fiddler, the event handler would get triggered, but the custom header would never get added to the request. It turns out that this approach schedules a PSEventJob to run your script block, which doesn’t end up returning the modified event argument back to the original source event object. Prompted by a good hint from this StackOverflow post, I was able to make use of PowerShell’s ability to create on-the-fly .net code and execute it. I wrapped it up in a function that you can call in your scripts. First you add the function:

Then, you create your ClientContext and call the function to add the event handler:

Below is a full gist with the solution:

One comment on “Accessing Mixed-Mode SharePoint Web Applications with CSOM and PowerShell
  1. They told me we could not use PowerShell to connect to our SharePoint environment. I insisted it had to be possible. Just like you I first tried to translate the C# event to PowerShell, but it didn’t work. However, the final solution you provided did work! Thanks for this great post, it proves that we can use PowerShell (even in our environment) to interact with SharePoint.

Comments are closed.