This PowerShell script allows to upload files for branding like css, js, html etc. to Master Page Gallery and allows set the custom master page and theme to the site. This uses CSOM and can be used for both SharePoint On-Prem and Online. This also creates a folder inside Master Page Gallery with the name provided in script where all files will be uploaded.

 

PowerShell
Edit|Remove
$scriptdir = $PSScriptRoot 
Set-Variable -Name "scriptPath" -Value $scriptdir -Scope Global 
 
Write-Host "Loading the CSOM library" -foregroundcolor black -backgroundcolor yellow 
Add-Type -Path "C:\Users\danish.i\Desktop\Deploy\Deploy\Microsoft.SharePoint.Client.dll" #update this path 
Add-Type -Path "C:\Users\danish.i\Desktop\Deploy\Deploy\Microsoft.SharePoint.Client.Runtime.dll" #update this path 
Add-Type -Path "C:\Users\danish.i\Desktop\Deploy\Deploy\Microsoft.SharePoint.Client.Publishing.dll" #update this path 
Write-Host "Succesfully loaded the CSOM library" -foregroundcolor black -backgroundcolor green 
 
 
$scriptdir = $PSScriptRoot 
Set-Variable -Name "scriptPath" -Value $scriptdir -Scope Global 
 
#Declare Global Variables 
$SiteUrl = "<URL of the site>" 
$Web = "" 
$online = $true 
 
Write-Host "Please provide username" 
$username = Read-Host 
 
Write-Host "Please provide password" 
$securedPassword = Read-Host -Prompt "Enter password" -AsSecureString 
 
Write-Host "Create client context for site $SiteUrl" -foregroundcolor black -backgroundcolor yellow 
$context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) 
 
#if true create context for SharePoint Online else for On-Prem 
if ($online) 
{ 
    Write-Host "Setting SharePoint Online credentials" -foregroundcolor black -backgroundcolor yellow     
    $context.AuthenticationMode = [Microsoft.SharePoint.Client.ClientAuthenticationMode]::Default     
    $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username$securedPassword) 
    $context.Credentials = $credentials 
} 
else 
{ 
    Write-Host "Setting SharePoint On-Prem credentials" -foregroundcolor black -backgroundcolor yellow     
    $credentials = New-Object System.Net.NetworkCredential($username$securedPassword) 
     
} 
    $context.Credentials = $credentials 
 
    Write-Host "Check connection" -foregroundcolor black -backgroundcolor yellow 
    $Web = $context.Web   
    $context.Load($Web) 
    $context.ExecuteQuery()  
 
 
write-host "Creating _TestA subfolder in Master Page Gallery..." -NoNewLine 
AddFolder -FolderName "_TestA" -WebURL $SiteUrl -ListName "Master Page Gallery" 
write-host "done" 
 
 
#call the upload function to upload necessary files 
UploadFile "Master Page Gallery" "_TestA" "logo.png" 
UploadFile "Master Page Gallery" "_TestA" "default.css" 
UploadFile "Master Page Gallery" "_TestA" "Danny.html" 
UploadFile "Theme Gallery" "15" "custom.spcolor" 
 
 
write-host "Updating Web to new branding..." -NoNewLine 
#Update the web masterpage and CSS 
$Web.MasterUrl = "$($Web.ServerRelativeUrl)/_catalogs/masterpage/_TestA/Danny.master" 
$Web.CustomMasterUrl = "$($Web.ServerRelativeUrl)/_catalogs/masterpage/_TestA/Danny.master" 
$Web.SiteLogoUrl = "$($Web.ServerRelativeUrl)/_catalogs/masterpage/_TestA/logo.png" 
$Web.AlternateCssUrl = "$($Web.ServerRelativeUrl)/_catalogs/masterpage/_TestA/default.css" 
$Web.Update() 
$context.ExecuteQuery() 
 
 
#apply the theme 
$fontUrl = Out-Null 
$bgImageUrl = Out-Null 
$Web.ApplyTheme($Web.ServerRelativeUrl + "/_catalogs/theme/15/custom.spcolor"$fontUrl$bgImageUrl$true$Web.Update() 
$context.ExecuteQuery() 
 
write-host "done" 
 
 
#function to create foder 
function AddFolder($FolderName$WebURL$ListName){ 
    
  if(!$Web){ 
   throw "No web exists with URL '$($SiteUrl)'" 
  } 
 
  $List = $Web.Lists.GetByTitle($ListName); 
  $context.Load($List) 
  $context.ExecuteQuery() 
   
  if(!$List){ 
   throw "$($ListName) does not exist in $($WebURL)" 
  } 
 
  $rootFolder = $List.RootFolder 
  $context.Load($rootFolder) 
  $context.ExecuteQuery() 
   
  $Folder = $Web.GetFolderByServerRelativeUrl($rootFolder.ServerRelativeUrl + "/" + $FolderName) 
  $context.Load($Folder) 
 
  try{ 
    $context.ExecuteQuery() 
  } 
  catch 
  { 
    $newFolder = $List.RootFolder.Folders.Add($FolderName); 
    $context.Load($newFolder); 
     
    $context.ExecuteQuery();           
    write-host "Folder Added" -ForegroundColor Green 
  } 
} 
 
#Function to Upload File 
function UploadFile($ListName$FolderPath$FileName) 
{ 
    write-host "Uploading $($FileName) to $($ListName)..." 
     
    $newSPFile = "" 
    $filePath = $scriptPath + "\" + $FileName 
    $File = Get-Item (Resolve-Path $filePath).Path 
    $fileBytes = [System.IO.File]::ReadAllBytes($File.FullName) 
    $fileinfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation 
    $fileinfo.Content = $fileBytes 
    $fileinfo.Url = $File.Name 
    $fileinfo.Overwrite = $false 
 
    #Get Lists to upload the file     
    $List = $Web.Lists.GetByTitle($ListName) 
    $context.Load($List) 
    $context.ExecuteQuery() 
   
    $rootFolder = $List.RootFolder 
    $context.Load($rootFolder) 
    $context.ExecuteQuery() 
 
    $Folder = $Web.GetFolderByServerRelativeUrl($rootFolder.ServerRelativeUrl + "/" + $FolderPath) 
    $context.Load($Folder) 
    $context.ExecuteQuery() 
     
    $destUrl = $Web.GetFileByServerRelativeUrl($Folder.ServerRelativeUrl + "/" + $FileName) 
    $context.Load($destUrl) 
 
    try{ 
        $context.ExecuteQuery() 
        $newSPFile = $destUrl 
    } 
    catch{ 
        #Get the Folder     
 
        $newSPFile = $Folder.Files.Add($fileinfo) 
        $context.Load($newSPFile) 
        $context.ExecuteQuery() 
 
        if($File.Name -like "*.html") 
        { 
            $masterPageContentTypeId = "0x0101000F1C8B9E0EB4BE489F09807B2C53288F0054AD6EF48B9F7B45A142F8173F171BD10003D357F861E29844953D5CAA1D4D8A3A00C79D1E7C67F0AA468B4AC8DDC46D0E5E" 
            $listItem = $newSPFile.ListItemAllFields 
            $listItem["ContentTypeId"] = $masterPageContentTypeId 
            $listItem.Update() 
            $context.ExecuteQuery() 
        } 
    } 
    finally{ 
        if($List.EnableVersioning) 
        { 
            if($newSPFile.CheckOutType -ne "None") 
            { 
                $newSPFile.CheckIn("Override check in",[Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn);              
                $context.ExecuteQuery() 
               
                $outputText = "Success:" + $File.Name + "  Uploaded on: " + $Folder.ServerRelativeUrl 
                write-output $outputText 
            } 
            else 
            { 
                $newSPFile.CheckOut() 
                $context.Load($newSPFile) 
                $context.ExecuteQuery() 
 
                $newSPFile.CheckIn("Override checkin.",[Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn); 
                 
                if($File.Name -like "*.html") 
                { 
                    $newSPFile.Publish("Publish a major version") 
                } 
                $context.ExecuteQuery() 
                 
                $outputText = "Success:" + $File.Name + "  Uploaded on: " + $Folder.ServerRelativeUrl 
                write-output $outputText 
                       
            } 
        } 
         
    } 
 }