The ability to easily attach/detach SQL databases when testing is incredibly valuable. Whilst working on a procedure to restore corrupted data in a database I had to create some scripts to automate attaching and detaching of SQL Server databases.

I thought I would share the scripts as they can be easily added to any existing scripts to help automate attaching database clones based on Pure snapshots.

First thing to do is create a AttachDatabasesConfig.xml file to list the databases and their corresponding data/log files to be attached. Here is an example: –

How to Detach SQL Server Databases

Detach-SQLDatabases.ps1; this is the same script as in the Attach-SQLDatabases.ps1 except for the $attachSQLCMD statement using sp_detach.

How to attach SQL Server Databases

Once the XML configuration file is created, the following script will retrieve the information in the file and attach the databases to a target instance: –