Office 365 - Automating the Creation of a Design Manager Package using CSOM with PowerShell

One of the really cool features in SharePoint 2013 is the Design Manager, further information on this feature can be found here: Overview of Design Manager in SharePoint 2013 - https://msdn.microsoft.com/en-us/library/jj822363.aspx.

Design Manager provides the ability to export a Design Manager Package so that customizations can be easily copied to another Site Collection and re-used - potentially saving a lot of time and hassle, the package itself is a sandbox solution using the WSP file format. A screenshot of the option can be found below:

Wouldn't it be cool if you could automate the creation of a Design Manager Package using PowerShell? Below is a PowerShell script that uses CSOM to perform this very task! The resultant package is saved to a local drive for re-use.

The three highlighted variables need to be updated. $Username is the username of an administrator of the Site Collection, $Site is the URL of the Site Collection and $DestinationDir is the local directory to save the exported package to.

#Please install the SharePoint client components SDK - https://www.microsoft.com/en-us/download/details.aspx?id=35585
$Username = "admin@tenant.onmicrosoft.com"
$Site = "https://tenant.sharepoint.com/sites/site"
$DestinationDir = "D:\Downloads\"

#Add references to SharePoint client assemblies and authenticate to Office 365 site
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($Site)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username,$Password)
$Context.Credentials = $Creds

$SC = $Context.Site
$Context.Load($SC)
$Context.ExecuteQuery()

$RootWeb = $SC.RootWeb
$Context.Load($RootWeb)
$Context.ExecuteQuery()

$DP = [Microsoft.SharePoint.Client.Publishing.DesignPackage]::ExportEnterprise($Context,$SC,$False)
$Context.ExecuteQuery()

#Download Design Package
$Package = $SC.ServerRelativeUrl + "/_catalogs/Solutions/" + $RootWeb.Title + "-1.0.wsp"
$Destination = $DestinationDir + $RootWeb.Title + "-1.0.wsp"
$FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Context,$Package)
$WriteStream = [System.IO.File]::Open($Destination,[System.IO.FileMode]::Create);
$FileInfo.Stream.CopyTo($WriteStream)
$WriteStream.Close();

Brendan Griffin - @brendankarl