Backing up and restoring a site collection using PowerShell is a pretty straight forward task and you can read the documentation for Backup-SPSite at

The unattached database restore feature which was introduced in SharePoint 2010 let's you access a copy of a database which you've restored to SQL (perhaps last night's backup) then use the Central Administration site to connect to that database and perform a backup of content (like a site collection backup for example). Articles such as do a good job of walking you though the process.

But what if you want to complete the whole process using PowerShell?

The trick is to use Get-SPContentDatabase to get a reference to the restored unattached database and pipe it to Get-SPSite.

This example allows you to specify the name of an existing production site collection and have it restored from the unattached database back into production.

$restoredDatabase = "myRestoredDatabase"
$databaseServer = "devlab01"
$siteCollectionToRestore = "http://devlab01"
$backupLocation = "c:\temp\unattachedSite.bak"

$unattachedDB = Get-SPContentDatabase -ConnectAsUnattachedDatabase -DatabaseName $restoredDatabase -DatabaseServer $databaseServer
$productionSite = Get-SPSite $siteCollectionToRestore
$unattachedSite = $unattachedDB | Get-SPSite | ? { $_.Id –eq  $productionSite.Id }; See Notes
Backup-SPSite $unattachedSite -Path $backupLocation
Restore-SPSite $productionSite.Url -Path $backupLocation -Force -Confirm:$false


Why do we need to perform the "$unattachedSite = $unattachedDB | Get-SPSite | ? { $_.Id –eq  $productionSite.Id };" stuff for? The problem is that despite this being referred to as an "unattached" restore, the fact is the database IS attached to the central administration web app (however you can't actually browse to them). When the attaching takes place, the URL changes of course and whilst the site collection you want to restore might be at http://intranet/sites/myimportantsite by the time it's attached to central administration it's called http://myspserver:8081/sites/myimportantsite. Since the Id is a unique GUID which identifies the site collection in a content database we can find the Id of the project site collection and use this to locate the same site in the restored database.

Note also that once the site collection has been restored (on the top of the existing production one) it actually gets a new GUID. So whilst you can run the script above once and it will run correctly, running it again will fail because it can't find a match between the GUID in production and the restored database.