Thursday, March 10, 2016

SharePoint Online - JavaScript Injection with PowerShell

Updating the Master Page for SharePoint Online is not recommended by Microsoft now.....fine. So how do we change the UI then? And the answer injecting JavaScript and CSS.

You might want to watch this video of JavaScript injection which we will not follow here as injecting JavaScript and/or CSS through Visual Studio takes little bit of time as shown in the above video so I am putting pieces together to inject JavaScript using PowerShell very very...very quickly. Thank you Office Dev PnP's Erwin van Hunen.

Note: We are not going to use SharePoint Online Management Shell ;o) instead we will use Windows PowerShell.
  1. Install PnP PowerShell Cmdlets for SharePoint Online
  2. Perform a quick test: Run the command below in Windows PowerShell to see if it is available
     Get-Command Add-SPOJavaScriptBlock
  3. Connect to the site where you want to push JavaScript code:
  4. Push the JavaScript code.
    Add-SPOJavaScriptBlock -Name MyScript -Script "alert('Hello World');"
    Add-SPOJavaScriptLink -Name JQuery -Url
  5. You are done. Now browse the site and you will get the annoying Hello World alert on all the pages.
Here is the complete script:
# This is a sample script and is provided as is.
# Author: Tahir Naveed
# Description: This script connects to a SPO site and 
# injects a JavaScript code block which will execute on all of the pages.

$url = ""
$ScriptName = "MyScript"
$scriptBlock = "alert('Hello World');"

    #Connect to the SPO site
    Connect-SPOnline $url
    #Remove script if added before
    Remove-SPOJavaScriptLink -Name $ScriptName

    #Add the script
    Add-SPOJavaScriptBlock -Name $ScriptName -Script $scriptBlock

    Write-Host "$_.Exception.Message"

Write-Host "Completed successfully." -ForegroundColor Green
Ref: Introduction to PnP PowerShell Cmdlets
Ref: OfficeDev/PnP-PowerShell Reference

Thursday, March 3, 2016

SharePoint - Export/Import Subsite


Lets suppose we have two SharePoint 2013 site collections and we want to export a sub-site from one site collection to another using PowerShell, then below is the answer.


Export: Export-SPWeb "" -Path "C:\Temp\Export.cmp"
Import: Import-SPWeb "" -Path "C:\Temp\Export.cmp"

Note: All the list, libraries, documents etc will get exported except for the workflows.


Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: