Export-SPWeb Syntax Changes Between Root Site and Sub Sites

Working on a somewhat related issue today and needed to test something with Export-SPWeb. We were trying to import a list from an STP (List template) and in order to get there I decided to export one of my own lists and play around a bit. Much to my surprise I was unable to export a custom list from my lab environment. I kept getting the following error:

 

 export-spweb : The URL provided is invalid. Only valid URLs that are site 
  collections or sites are allowed to be exported using stsadm.exe. 
  At line:1 char:1 
  + export-spweb $web -Path exported_list.cmp -ItemUrl "/lists/testlist" 
  -Force 
  + 
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
  + CategoryInfo : InvalidData: (Microsoft.Share...CmdletExportWeb: 
  SPCmdletExportWeb) [Export-SPWeb], SPException 
  + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletExportWeb

 

It was quite maddening as the parameters are not that difficult to figure out. (get-help export-spweb)

So I was trying many things and discovered that in a second lab environment I had that it worked flawlessly and I was determined to discover why. The first thing that a peer of mine found for me was that in the failing environment the web from which I was trying to export the custom list was on a site collection under the ‘sites’ managed path (in other words not the root site). The environment that was working was the root site collection.

To cut to the chase, you may not be able to use the same syntax depending on where the list resides. The parameter in question that kept failing for me was the ItemUrl parameter. It is to represent the url to the list that you would like to export. Basically if the site collection is the root site collection, then the ItemUrl should contain a leading “/” such as this:

Export-SPWeb https://intranet.contoso.lab –Path exported_list.cmp –ItemUrl “/Lists/TestList”

However if the site collection is not the root, then you should either include the full server relative url to the list or the web relative url to the list *without* the leading slash:

Export-SPWeb https://intranet.contoso.lab/sites/TestImport –Path exported_list.cmp –ItemUrl “/sites/TestImport/Lists/TestList”

or

Export-SPWeb https://intranet.contoso.lab/sites/TestImport –Pat exported_list.cmp –ItemUrl “Lists/TestList”

If you care to know, basically under the covers the Export-SPWeb cmdlet will call SPWeb.GetList(), but prior to calling that function it will prepend the SPWeb.ServerRelativeUrl and an extra “/” if the string in ItemUrl does not have a leading “/”. In short, to be safe if you always set the ItemUrl parameter to the server relative url and then path to the list, it should always work regardless of web location.