0% found this document useful (0 votes)
6 views

Powershell SQLBackupScript

The function runs a local SQL query using either sqlcmd or osql depending on availability. It takes a query as a parameter, runs it using the appropriate tool with SA credentials and specified database, and returns a status. The sample code then declares variables, backs up a database to a file, gets the backup ID, and verifies the backup without restoring for validation.

Uploaded by

halljps
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Powershell SQLBackupScript

The function runs a local SQL query using either sqlcmd or osql depending on availability. It takes a query as a parameter, runs it using the appropriate tool with SA credentials and specified database, and returns a status. The sample code then declares variables, backs up a database to a file, gets the backup ID, and verifies the backup without restoring for validation.

Uploaded by

halljps
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

function RunLocalSQLQuery($query)

IF ((Get-Command "sqlcmd" -ErrorAction SilentlyContinue))

sqlcmd -U sa -P <INSERT PWD> -d <INSERT DB NAME> -w 4096 -y 29 -Y 29 -Q $query

return 1

ELSEIF ((Get-Command "osql" -ErrorAction SilentlyContinue))

osql -U sa -P <INSERT PWD> -d <INSERT DB NAME> -w 4096 -y 29 -Y 29 -Q $query

return 1

ELSE

return 0

$query = @"

Declare @MTDB2 NVARCHAR(255)

Select @MTDB2 = DatabaseName

from #TempMaintenanceLog

where Command = 'CheckDBName'

BACKUP DATABASE @MTDB2

TO DISK = N'C:\Octopus\<DBNAME>.bak' WITH RETAINDAYS = 5,

FORMAT,

INIT,

MEDIANAME = N'<DBNAME>.bak',

NAME = N'<DBNAME>-Full Database Backup',

SKIP,

NOREWIND,
NOUNLOAD,

STATS = 10

GO

Declare @backupSetId as int

Select @backupSetId = position

From msdb..backupset

Where database_name=N'<DBNAME>'

and backup_set_id=(select max(backup_set_id)

From msdb..backupset

Where database_name=N'<DBNAME>' )

If @backupSetId is null

Begin

raiserror(N'Verify failed. Backup information for database ''<DBNAME>'' not found.', 16, 1)

SET NOEXEC ON

End

RESTORE VERIFYONLY FROM DISK = N'C:\Octopus\<DBNAME>.bak'

WITH FILE = @backupSetId,

NOUNLOAD,

NOREWIND

GO

"@

RunLocalSQLQuery($query)

You might also like