Copying SharePoint 2010 Document Libraries with PowerShell

The following problem is a great example of one of those SharePoint situations where you imagine that the job at hand will be relatively straightforward. But that sadly turns on you with some unexpectedly unsupported scenarios that require going deep down the SharePoint API rabbit hole. These are the original requirements.

Given a Site Collection with dummy site defined within it.

The user should be able to modify the dummy site and store it as a template.

The user has to be able to create any number of sites, which will replicate the structure of the template itself.

This structure includes any number of lists and sample data, i.e. placeholders

The permissions must be kept exactly like in the the template. The permissions might not necessarily be "inherited".

Well, covering the first 4 bullets points is pretty average SP fare. However, none of the standard mechanisms to create templates or export site definitions will respect a custom permission structure that breaks the default inheritance.

These are the standardish methods that I initially tried when attempting to replicate the site templates.

And here's the workaround that I put together with the help of some PowerShell. There is still a bit of manual processing, but it is infinitely better than having to define all permissions from scracth.

Create a root site with the desired structure and content

Save a template of the site with the standard SharePoint method (bullet point #1 in the previous list)

Create the document libraries and define their custom permissions

Create a new site from the template saved in step #2. (we are of course, missing the libraries created in step #3)

Use the PowerShell script below to copy and replicate the structure of the libraries defined in step #3

Repeat steps 4 and 5 for any other sites that apply.
To configure the script you only need to change its very last line, which is a call to a recursive function.