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 
1.$Path
2.$dbName
3.$instance 


function Get-SnapshotScriptFileLine([string]$fileName, [string]$data_path)
{
       return "( NAME = {0}, FILENAME = '{1}\{0}.ss')," -f $fileName, $data_path
}
 
$path="E:\Backup"
$dt = Get-Date
$fileNameVar = $dt.ToString("yyyyMMddhhmmss")
$dbName="myDBName"
$snapshotName = [string]::Format("{0}_{1}_snap", $dbName, $fileNameVar)
$instance="myServerName\SQL2016"
 
$conString="Server=$instance;database=$dbname;trusted_connection=true;"
#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 
#

Advertisements
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:

WordPress.com Logo

You are commenting using your WordPress.com 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