简体   繁体   中英

Powershell alter Backup Scripts for SQL Server

I am trying to assist my System Administrator by writing a Powershell script that takes parameters and will translate that into a backup script for several SQL Server databases that need to be backed up before and after our deployments.

I would ideally like to allow him to input these params:

@Database = 'Genesis'
@BackupName = 'Genesis_backup'
@BackupDate = '2016_01_20'
@BackupDateTime = '2016_01_20_01340_3181013'
@Location = 'E:\SQLBackup\TEST'

So if this is the backup string

BACKUP DATABASE [@Database] TO  DISK = N'E:\SQLBackup\TEST - 20160120\Genesis_backup_2016_01_20_01340_3181013.bak' WITH NOFORMAT, NOINIT,  NAME = N'Genesis_backup_2016_01_20_01340_3181013', SKIP, REWIND, NOUNLOAD, COMPRESSION,  STATS = 10
GO

I would like Powershell to build it to look like

BACKUP DATABASE [Genesis] TO  DISK = N'@Location - @BackupDate\@BackupName_@BackupDateTime.bak' WITH NOFORMAT, NOINIT,  NAME = N'@BackupName_@BackupDateTime', SKIP, REWIND, NOUNLOAD, COMPRESSION,  STATS = 10
GO

How would I start something like this out? What functions would you recommend I use for this? Also how do I parse out the locations dynamically?

There are two ways: use straight TSQL (favored by the DBA crowd) or use Sql Server's SMO API (more Powershell-ish, emulates SSMS wizards). As a lot of DBA people are more familiar with TSQL, it's easier to get help with the TSQL path.

Instead of rolling your own solution, a popular approach is to use Ola Hallengren's maintenance solution which includes tried and true backup procedures. Ola's solution uses Sql Server Agent jobs for scheduling, so Sql Express needs to use, say, Task Scheduler. With Ola's stuff, just create additional an agent job which backs up the databases you want. Agent jobs can be started by executing sp_start_job sproc. This can be done with, say, sqlcmd or Powershell's Invoke-SqlCmd .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM