I
needed a powershell script to quickly backup or restore SQL database’s before doing maintenance work, but without having to remote into an SQL server. With this task in hand I wrote the below module. I’ve sealed this as a module to be imported on runtime so you can quickly run a backup before making any changes to infrastructure utilising sql, safe with the knowledge you have a backup, and more importantly restore if you make a mess of it!
This module should be used before using my xenapp 6 backup, reset and restore commands or Edgesight scripts. You can get a copy of it here.
To import the module, run the below command (assuming you have saved the module to c:).
import-module c:sql.backup.psm1
Module functions:
- Backup-SQLdatabase
- Restore-SQLdatabase
Backup-SQLdatabase
This module allows you to connect to an SQL server and use native SQL commands to perform the backup to a file from pretty much any windows machine with powershell installed.
This module supports trusted and untrusted connections and has built in error checking to catch typical problems and returns a job report as an object. The module will first try to connect and ensure you have the neccessary access rights, attempt to create the backup file, and assuming all has gone well then perform the task at hand:
[sourcecode language=”Powershell”]
Backup-SQLdatabase -SQLServer "sqlserver" -SQLDatabase "database" -Path "servershare$backup.bak" -SQLTrustedConnection
[/sourcecode]
(Private information ommitted)
Restore-SQLDatabase
This module allows you to connect to an SQL server and use native SQL commands to perform a restore from a file from pretty much any windows machine with powershell installed.
This module supports trusted and untrusted connections and has built in error checking to catch typical problems and returns a job report as an object. The module will first try to connect and ensure you have the neccessary access rights, attempt to locate the backup file, set the sql database to single user mode and assuming all has gone well then perform the task at hand.
[sourcecode language=”Powershell”]
restore-SQLdatabase -SQLServer "sqlserver" -SQLDatabase "database" -Path "servershare$backup.bak" -SQLTrustedConnection
[/sourcecode]
(Private information ommitted)
If for any reason, the restore doesn’t work correctly the function will take the corrective action of setting the database back to multi-user.
A full copy of the module to be viewed can be found after the jump below:


















