SharePoint 2013 Design Packages: Import with PowerShell (Part 2 of 2)

Last Thursday I wrote about “Exporting SharePoint 2013 Design Packages with PowerShell”. Today I’d like to show you the import function. This functions can be used to handle with SharePoint 2013 Design Packages with PowerShell, e.g. in deployment scenarios. Therefore it should by very useful. (I hope so ;-) ) FEEDBACK WELCOME!!!

You can download the scripts here:

http://gallery.technet.microsoft.com/Export-and-Import-0f41b376

Here you can find the blog article about “Export-SPDesignPackage”: http://blog.karstein-consulting.com/2013/02/14/sharepoint-2013-design-packages-export-with-powershell-part-1-of-2

 

The import function is called “Import-SPDesignPackage” and here are the details:

Import-SPDesignPackage

Here are some samples

#First sample

Import-SPDesignPackage -SiteUrl "http://sharepoint.local/publishing" -ImportFileName "C:\temp\publishing2.wsp" -PackageName "P2" -Apply $true

#Second sample


(
    @{ SiteUrl ="http://sharepoint.local/sites/publishing1";
       ImportFileName ="C:\temp\publishing1.wsp";
       PackageName ="P1";
       Apply=$true
    },
    @{ SiteUrl ="http://sharepoint.local/sites/publishing2";
       ImportFileName ="C:\temp\publishing2.wsp";
       PackageName ="P2";
       Apply=$true
    }
) | New-ObjectFromHashtable | Import-SPDesignPackage

The first sample shows you how to import one design package to a dedicated site. By using the “Apply” parameter the design package will be applied to the site immediately.

The second sample shows you hot to import two different packages to two different site collections. In the sample I use a hashtable for input parameters. They are assigned to the function parameters by “property name binding”. See “http://technet.microsoft.com/en-us/library/hh847743.aspx”: Section “ValueFromPipelineByPropertyName”:

[…]
For example, if the function has a ComputerName parameter, and the 
piped object has a ComputerName property, the value of the ComputerName
property is assigned to the ComputerName parameter of the function.

The following example declares a ComputerName parameter that is 
mandatory and accepts input from the ComputerName property of the 
object that is passed to the function through the pipeline.
[…]

Some more details about that. Skip it if you are not interested…

 

<begin/>

 

This “property name binding” does not work with hashtables. Therefore I created a helper function “New-ObjectFromHashtable” that creates a PowerShell object (“PSObject”). This function is generic. (It’s also included in the script files.)

 

On the one hand with “new-object System.Management.Automation.PSObject” you can create a new “empty” PowerShell object that can be used in your script as every other object, e.g. a SharePoint object like an instance of class SPSite. With cmdlet “Add-Member” you can add new members to the object. – On the other hand you have a hashtable with named values. You can access the collection of names = keys and with each key you can access the value. – Let’s combine it: You can iterate through the keys collection and create a new member in an empty PSObject instance.

 

functionNew-ObjectFromHashtable {
    #written by Ingo Karstein (http://blog.karstein-consulting.com)# v1.0#Use this function to convert a hashtable to a PowerShell object ("PSObject"), e.g. for using hashtables for property name binding in# PowerShell pipelines
    [CmdletBinding()]
    param(
        [parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
        [Hashtable]
        $Hashtable
    )

    begin {
        $results= @()
    }

    process {
        $r=new-objectSystem.Management.Automation.PSObject$Hashtable.Keys | % {
            $key=$_$value=$Hashtable[$key]
            $r | Add-Member-MemberTypeNoteProperty-Name$key-Value$value-Force
        }

        $results+=$r
    }

    end {
        $results
    }

}

The resulting object can be passed to each “property name binding” enabled cmdlet. – The PowerShell engine tries to match input object property names and cmdlet parameter names. If there is a match the input object property value gets assigned to the cmdlets input parameter.

 

The cmdlet can also convert a list of hashtables to a list of objects. That is used in the “Import-SPDesignPackage” script.

 

<end/>

Parameters

Parameter Name Parameter Set Name Mandatory? Position Description
SiteUrl Default Yes 0 Site Url for import
Site Site Yes 0 SPSite object for import
ImportFileName DefaultSite Yes 1 Filename and path of the design package for import
Apply DefaultSite Yes 2 $true = Apply the design package after import$false = Only install the design package for later activation
PackageName DefaultSite No 3 Package name. If not specified it uses the file name without extension. The package name will be used for naming the imported file in the solution gallery of the site collection
MajorVersion DefaultSite No - Version number of the design package. If not specified it uses “1” for the major version.
MinorVersion DefaultSite No - Version number of the design package. If not specified it uses “0” for the minor version.

 

The function returns an object for each processed (or not processed) site collection:

image

Object Property Description
SiteUrl Url of the processed site
Success $true = Import and “Apply” (if specified) was successful
InputFileFound $true = File found$false = File not found
InputFileExtensionValid $true = Input file has extension “.wsp”$false = Input file hat not extension “.wsp”
SiteFound $true = The specified site was found
SolutionFileName The name of the solution is auto generated from package name or file name and major and minor version number. This is the name of the package in the site collections solution gallery.
PackageAlreadyExsits $true = the solution does already exist in the solution gallery.

Some additions

The import process requires the package to be stored inside the site collection before the the last input step. Therefore the function creates a folder named “tmp_importspdesignpackage_15494B80-89A0-44FF-BA6C-208CB6A053D0” in the site collections root web root folder. In this folder the package gets uploaded. From the location the package is imported. The folder will be deleted after successful or not failed import.

8 Responses to “SharePoint 2013 Design Packages: Import with PowerShell (Part 2 of 2)”

  1. Vaibhav Chopra

    This doesnot work with Windows Server R2 SP1. I get the following error: Import-SPDesignPackage : The term ‘Import-SPDesignPackage’ is not recognized
    as the name of a cmdlet, function, script file, or operable program. Check the
    spelling of the name, or if a path was included, verify that the path is
    correct and try again. Any ideas? :)

    Reply
  2. Vaibhav Chopra

    My Bad! Premature reply. I assumed that the “import-SPDesignPackage” command is provided as a part of the Snapin. After downloading the script, it works like a charm. Thanks a ton. It saved a lot of effort. Cheers!

    Reply
  3. Dominic

    Hi,
    I got an error, if I want to import a designpackage to an TopicArea Template…

    System.Management.Automation.MethodInvocationException: Exception calling “Install” with “3″ argument(s): “Ein
    Ereignisempfänger hat die Anforderung abgebrochen.” —> Microsoft.SharePoint.SPException: Ein Ereignisempfänger
    hat die Anforderung abgebrochen. —> System.Runtime.InteropServices.COMException:
    0x81020089Ein Ereignisempfänger hat die Anforderung abgebrochen.
    at Microsoft.SharePoint.Library.SPRequestInternalClass.PutFile(String bstrUrl, String bstrWebRelativeUrl,
    Object punkFile, Int64 cbFile, Object punkSPFileMgr, Object punkFFM, Int64 PutFileOpt, String bstrCreatedBy,
    String bstrModifiedBy, Int32 iCreatedByID, Int32 iModifiedByID, Object varTimeCreated, Object varTimeLastModified,
    Object varProperties, String bstrCheckinComment, String bstrLockIdMatch, String bstEtagToMatch, Int32 lockType,
    String lockId, Int32 minutes, Int32 fRefreshLock, Int32 bValidateReqFields, Guid gNewDocId, SPFileSaveParams sfsp,
    SPFileInfo& pFileProps, UInt32& pdwVirusCheckStatus, String& pVirusCheckMessage, String& pEtagReturn, Byte&
    piLevel, Int32& pbIgnoredReqProps)
    at Microsoft.SharePoint.Library.SPRequest.PutFile(String bstrUrl, String bstrWebRelativeUrl, Object punkFile,
    Int64 cbFile, Object punkSPFileMgr, Object punkFFM, Int64 PutFileOpt, String bstrCreatedBy, String bstrModifiedBy,
    Int32 iCreatedByID, Int32 iModifiedByID, Object varTimeCreated, Object varTimeLastModified, Object varProperties,
    String bstrCheckinComment, String bstrLockIdMatch, String bstEtagToMatch, Int32 lockType, String lockId, Int32
    minutes, Int32 fRefreshLock, Int32 bValidateReqFields, Guid gNewDocId, SPFileSaveParams sfsp, SPFileInfo&
    pFileProps, UInt32& pdwVirusCheckStatus, String& pVirusCheckMessage, String& pEtagReturn, Byte& piLevel, Int32&
    pbIgnoredReqProps)

    May you can check this problem?? I’m a powershell newbe :( and I can’t read your function :D

    Reply
    • Douglas

      I have the same issue. Did you get a solution for this error with Exception calling “Install” with “3″ argument(s)

      Reply
      • Neeraj

        I was able to resolve the “The Install with 3 arguments error” by using the farm account to run the powershell…initially I tried to run the powershell with farm install account that doesn’t have farm admin access….Following are the steps I followed:
        1. Run install-module powershell command to install the powershell function provided by this powershell
        2. Run the Import-SPDesignPackae command with right parameters
        Everything worked like a charm….we are about to commence the migration of our entire 2010 farm to 2013 version which has 5 Web Apps and loads of site collectios….I can now traverse through all site collections and use this awesome powershell to apply the revamped branding to all site collections

        Reply
  4. Santhosh

    I am getting the following error in search template site collection. please do the needful.

    System.Management.Automation.MethodInvocationException: Exception calling “Install” with “3″ argument(s): “An event receiver has canceled the request.”
    —> Microsoft.SharePoint.SPException: An event receiver has canceled the request. —> System.Runtime.InteropServices.COMException:
    0x81020089An event receiver has canceled the request.
    at Microsoft.SharePoint.Library.SPRequestInternalClass.PutFile(String bstrUrl, String bstrWebRelativeUrl, Object punkFile, Int64 cbFile, Object
    punkSPFileMgr, Object punkFFM, Int64 PutFileOpt, String bstrCreatedBy, String bstrModifiedBy, Int32 iCreatedByID, Int32 iModifiedByID, Object
    varTimeCreated, Object varTimeLastModified, Object varProperties, String bstrCheckinComment, String bstrLockIdMatch, String bstEtagToMatch, Int32
    lockType, String lockId, Int32 minutes, Int32 fRefreshLock, Int32 bValidateReqFields, Guid gNewDocId, SPFileSaveParams sfsp, SPFileInfo& pFileProps,
    UInt32& pdwVirusCheckStatus, String& pVirusCheckMessage, String& pEtagReturn, Byte& piLevel, Int32& pbIgnoredReqProps)
    at Microsoft.SharePoint.Library.SPRequest.PutFile(String bstrUrl, String bstrWebRelativeUrl, Object punkFile, Int64 cbFile, Object punkSPFileMgr,
    Object punkFFM, Int64 PutFileOpt, String bstrCreatedBy, String bstrModifiedBy, Int32 iCreatedByID, Int32 iModifiedByID, Object varTimeCreated, Object
    varTimeLastModified, Object varProperties, String bstrCheckinComment, String bstrLockIdMatch, String bstEtagToMatch, Int32 lockType, String lockId, Int32
    minutes, Int32 fRefreshLock, Int32 bValidateReqFields, Guid gNewDocId, SPFileSaveParams sfsp, SPFileInfo& pFileProps, UInt32& pdwVirusCheckStatus,
    String& pVirusCheckMessage, String& pEtagReturn, Byte& piLevel, Int32& pbIgnoredReqProps)
    — End of inner exception stack trace —
    at Microsoft.SharePoint.SPGlobal.HandleComException(COMException comEx)
    at Microsoft.SharePoint.Library.SPRequest.PutFile(String bstrUrl, String bstrWebRelativeUrl, Object punkFile, Int64 cbFile, Object punkSPFileMgr,
    Object punkFFM, Int64 PutFileOpt, String bstrCreatedBy, String bstrModifiedBy, Int32 iCreatedByID, Int32 iModifiedByID, Object varTimeCreated, Object
    varTimeLastModified, Object varProperties, String bstrCheckinComment, String bstrLockIdMatch, String bstEtagToMatch, Int32 lockType, String lockId, Int32
    minutes, Int32 fRefreshLock, Int32 bValidateReqFields, Guid gNewDocId, SPFileSaveParams sfsp, SPFileInfo& pFileProps, UInt32& pdwVirusCheckStatus,
    String& pVirusCheckMessage, String& pEtagReturn, Byte& piLevel, Int32& pbIgnoredReqProps)
    at Microsoft.SharePoint.SPFileCollection.AddStreamOrBytesInternal(String urlOfFile, Stream file, Int64 fileSizeToSave, SPFileStreamManager spmgr,
    PutFileOpt fileOpt, String createdBy, String modifiedBy, Int32 createdByID, Int32 modifiedByID, DateTime timeCreated, DateTime timeLastModified, Object
    varProperties, String checkInComment, Stream formatMetadata, String lockIdMatch, String etagToMatch, SPLockType lockType, String lockId, TimeSpan
    lockTimeout, Boolean validateRequiredFields, SPVirusCheckStatus& virusCheckStatus, String& virusCheckMessage, String& etagNew, Boolean&
    ignoredRequiredProps)
    at Microsoft.SharePoint.SPFileCollection.Add(String urlOfFile, Stream file, Boolean overwrite, String checkInComment, Boolean checkRequiredFields)
    at Microsoft.SharePoint.SPFileCollection.Add(String urlOfFile, Stream file, Boolean overwrite)
    at Microsoft.SharePoint.Publishing.DesignPackage.c__DisplayClass1.b__0()
    at Microsoft.SharePoint.SPSecurity.c__DisplayClass5.b__3()
    at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
    at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
    at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
    at Microsoft.SharePoint.Publishing.DesignPackage.Install(SPSite site, DesignPackageInfo info, Stream data)
    at Microsoft.SharePoint.Publishing.DesignPackage.Install(SPSite site, DesignPackageInfo info, String path)
    at CallSite.Target(Closure , CallSite , RuntimeType , Object , Object , Object )
    — End of inner exception stack trace —
    at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
    at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
    at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
    at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

    Reply

Leave a Reply