Export web parts to xml using PowerShell

Here is a very handy PowerShell script that can speed up your web part development in SharePoint. It is a common scenario when you configure an OOB web part, and then you want to export it to XML  in order to integrate it in your custom solution for future deployments. This can occur in various scenarios, and with the arrival of the SharePoint 2013, it will become even more frequent. It works great in SharePoint 2010 also. I find it very helpful especially when working with search verticals, but it can be used in many other situations.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function EnsureDirectory($exportFolderPath)
 if ( -not (Test-Path $exportFolderPath) ) {New-Item $exportFolderPath -Type Directory | Out-Null}

function ExportAllWebParts($siteUrl,$pageUrl,$exportFolderPath)
 $web = Get-SPWeb $siteUrl
 $wpm = $web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

EnsureDirectory $exportFolderPath

foreach($wp in $wpm.WebParts)
 $exportPath = $exportFolderPath + "\" + $wp.Title + ".xml"
 $xwTmp = new-object System.Xml.XmlTextWriter($exportPath,$null);
 $xwTmp.Formatting = 1;#Indent
 $wpm.ExportWebPart($wp, $xwTmp);

ExportAllWebParts $args[0] $args[1] $args[2]

# I use this script as a file, ExportWebParts.ps1. The required arguments for this script should be:
#The site absolute URL
#The page site-relative URL
#The folder path for export

#example usage ./ExportWebParts.ps1 http://spdevel.portal.com/ Pages/default.aspx C:\temp\Export 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: