Generate SQL Query for Database Snapshot creation using Powershell

Following PowerShell script generates SQL Query to take a snapshot;

## Following 3 parameters needs to be updated in the script 

function Get-SnapshotScriptFileLine([string]$fileName, [string]$data_path)
       return "( NAME = {0}, FILENAME = '{1}\{0}.ss')," -f $fileName, $data_path
$dt = Get-Date
$fileNameVar = $dt.ToString("yyyyMMddhhmmss")
$snapshotName = [string]::Format("{0}_{1}_snap", $dbName, $fileNameVar)
#Load all SQL necesssary assemblies
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMo") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMoExtended") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMoEnum") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = $conString
$sqlConnection.Open() | Out-Null
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($instance)
$database = $server.Databases[$dbName]
foreach ($filegroup in $database.FileGroups) {
    foreach ($datafile in $filegroup.Files) {
        $fileLine = Get-SnapshotScriptFileLine -fileName $datafile.Name -data_path $path
        $filesForSS = $filesForSS + "`r`n{0}" -f $fileLine
$filesForSS = $filesForSS -replace ".$"
$script = "USE MASTER`r`n CREATE DATABASE {0} ON`r`n {1}`r`n AS SNAPSHOT OF {2}" -f $snapshotName, $filesForSS, $dbName
Write-Host $script 

This entry was posted in Powershell, Productivity, SQL, Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s