Automating Internet Explorer using PowerShell and resetting Alternate CSS URL

I was using remote provisioning to set the alternate CSS URL for a SharePoint site but found that, when doing so, the subsites were not applied. When you set the alternate CSS URL property using the server-side API, it does apply to subsites.

Instead, I wrote a small script that automates all this using the Internet Explorer browser hook in PowerShell.

Helper Methods

First, I need a global window to work with as I do not want to reopen IE for everything I do.

function Init-Browser {
    # Load IE instance
    if ($global:ie -eq $null) {
        $global:ie = new-object -ComObject "InternetExplorer.Application"
        $global:ie.visible = $true
        $global:ie.silent = $true

    return $global:ie

The visible flag above is used to show progress during the call. If you prefer to hide it, use $false here.

I also needed some functions to wait for when the browser is busy loading.

function Wait-Browser {
    while($global:ie.Busy) { Start-Sleep -Milliseconds 100 }

Then, I need a function to load a URL. In this case, if we use ADFS and the authentication has expired, I ask the user to log on manually.

function Navigate ([string]$url) {


    if ($global:ie.LocationUrl.ToLower().Contains("adfs")) {
        Write-Host "Browser requires authentication. Please log on manually then press enter." -ForeGroundColor Cyan
        $wait = Read-Host

I also have a function for executing scripts, in particular jQuery.

function Execute-Script($code) {
    $global:ie.Document.parentWindow.execScript($code, "javascript");

I then have a common function to close the browser when I am done will all automation.

function Close-Browser {
    $global:ie = $null

Resetting the Alternate CSS URL

Finally, I use the script below to reset the stylesheet on all subsites. The comments below should be self explanatory.

function Reset-AlternateStylesheet([string]$siteUrl) {

    $url = $siteUrl
    if (!($url.EndsWith("/"))) {
        $url += "/"
    $url += "_layouts/15/ChangeSiteMasterPage.aspx"

    Navigate $url 

    # Open the Alternate CSS Url area
    Execute-Script '$("#ctl00_PlaceHolderMain_ctl03").show()'

    # Select custom CSS
    Execute-Script '$("label[for=''ctl00_PlaceHolderMain_ctl03_ctl01_selectAlternateCssRadioButton'']").click()'

    # Enable "Reset all subsites"
    Execute-Script '$("label[for=''ctl00_PlaceHolderMain_ctl03_ctl01_resetAlternateCssSubSitesCheckBox'']").click()'

    # Click the OK button
    Execute-Script '$("#ctl00_PlaceHolderMain_ctl04_RptControls_ButtonSaveSettings").click()'