SlideShare a Scribd company logo
Restoring SQL Server databases
using Powershell
Johan Bijnens
#ITPROceed
Johan Bijnens
• Who am I ?
– SQLServerCentral.com
– @alzdba
• CERA – KBC Bank (1988 – 1999)
– Assembler / Cobol / APS / SAS / JCL
– VSAM / IMSdb / DB2
• ALZ – Ugine&ALZ – Arcelor – ArcelorMittal -
– PLI / Cobol / VBS / VB.net
– DB2
– SQLServer (7.0 – 2000 – 2005 – 2008 R2 – 2012 - 2014)
– Oracle
/ Powershell
Restoring Databases
using .
• Build plan of approach to structured point
in time restores of databases ( e.g. from
Production to QA ) using Powershell as an
easy helper tool to ensure all steps are
being performed.
Think
Know
Backup
• Backup:
• Minimise data loss in case of disaster
• RPO: Recovery Point Objective = Data loss
• RTO: Recovery Time Objective = Down time
• RSO: Recovery Service Objective = Disaster infrastructure needed
• SQL server database backup :
– Full: Copy of all active pages in your database into a file.
– Differential: Copy of all modified pages since the last Full backup
– Log: Copy of all database transactions since the last Log backup
– Checksum ( Exec sp_configure ‘backup checksum default’,1; Reconfigure )
• What good is a backup if you cannot restore it ?
The Setup
• # SQLServer instances have been set up to support the
different QA environments
• Every instance already has the databases pre-configured,
SQLUser accounts in place, windows domain groups, …
• Segregation of duties:
– different passwords
– Different windows domain groups
• Naming conventions help out to make it all work smooth.
• Keep It Simple & Stupid works !
The Setup
• Dev/QA teams:
– Have databases for which they are responsible
– Request ad-hoc data refresh for a given
database for which they have responsibility.
– point-in-time restore can be requested
– Approval by team leader
SQL Server and Powershell
• SQLPs:
– Powershell integration provided by Microsoft SQL
Server since 2008
– SQL 2012 provides module SQLPs
– SQL 2014 enhanced / extended SQLPs
– SQLAgent integration (job step)
- http://sqlpsx.codeplex.com/
SMO vs Powershell ?
• SQL Server Management Objects (SMO)
– SSMS
– object hierarchy and the relationships
– http://msdn.microsoft.com/en-
us/library/ms162209.aspx
– Namespaces for different areas of
functionality within SMO.
– Still needed in case SQLPs
• doesn’t cover the topic
• cannot handle it
SMO vs Powershell ?
• SMO namespaces:
– http://msdn.microsoft.com/en-us/library/ms162233.aspx
Class Function
Microsoft.SqlServer.Management.Smo Contains instance classes, utility classes, and enumerations
Microsoft.SqlServer.Management.Common Replication Management Objects (RMO) and SMO, such as connection classes.
Microsoft.SqlServer.Management.Smo.Agent SQL Server Agent.
Microsoft.SqlServer.Management.Smo.Wmi WMI Provider.
Microsoft.SqlServer.Management.Smo.RegisteredServers Registered Server. (SSMS)
Microsoft.SqlServer.Management.Smo.Mail Database Mail.
Microsoft.SqlServer.Management.Smo.Broker Service Broker.
SMO vs Powershell ?
• SQLPs:
– 46 Cmdlets that facilitate functionality
– Powershell programmers will be able to recognize parallels
– Discovery / get-help
get-command -module sqlps | sort noun, verb | ft -autosize
get-command -module sqlps |
sort noun, verb | Select Noun, Name| ft -autosize
Noun Name
PolicyEvaluation Invoke-PolicyEvaluation
SqlAlwaysOn Disable-SqlAlwaysOn
Enable-SqlAlwaysOn
SqlAuthenticationMode Set-SqlAuthenticationMode
SqlAvailabilityDatabase Add-SqlAvailabilityDatabase
Remove-SqlAvailabilityDatabase
Resume-SqlAvailabilityDatabase
Suspend-SqlAvailabilityDatabase
SqlAvailabilityGroup Join-SqlAvailabilityGroup
New-SqlAvailabilityGroup
Remove-SqlAvailabilityGroup
Set-SqlAvailabilityGroup
Switch-SqlAvailabilityGroup
Test-SqlAvailabilityGroup
SqlAvailabilityGroupListener New-SqlAvailabilityGroupListener
Set-SqlAvailabilityGroupListener
SqlAvailabilityGroupListenerStaticIp Add-SqlAvailabilityGroupListenerStaticIp
SqlAvailabilityReplica New-SqlAvailabilityReplica
Remove-SqlAvailabilityReplica
Set-SqlAvailabilityReplica
Test-SqlAvailabilityReplica
SqlBackupEncryptionOption New-SqlBackupEncryptionOption
Sqlcmd Invoke-Sqlcmd
Noun Name
SqlCredential Get-SqlCredential
New-SqlCredential
Remove-SqlCredential
Set-SqlCredential
SqlDatabase Backup-SqlDatabase
Get-SqlDatabase
Restore-SqlDatabase
SqlDatabaseReplicaState Test-SqlDatabaseReplicaState
SqlFirewallRule Add-SqlFirewallRule
Remove-SqlFirewallRule
SqlHADREndpoint New-SqlHADREndpoint
Set-SqlHADREndpoint
SqlInstance Get-SqlInstance
Start-SqlInstance
Stop-SqlInstance
SqlName Decode-SqlName
Encode-SqlName
SqlNetworkConfiguration Set-SqlNetworkConfiguration
SqlSmartAdmin Get-SqlSmartAdmin
Set-SqlSmartAdmin
Test-SqlSmartAdmin
UrnToPath Convert-UrnToPath
Basic functions with regards to
recovery
• Get-help Restore-SQLDatabase
• Restore-SqlDatabase -ServerInstance
‘serverinstance’ -Database ‘Db_Restored’
-BackupFile
‘J:MSSQL12.instanceMSSQLBackupDbFull.bak’
• Done! Right ?
Restoring is just a part
• Security
– Sqlusers / passwords
– Domain accounts
– Domain groups
• Integrity
– Detect physical / logical errors ASAP
– Backup corruption
– Restore corruption
Restore: Preparation
• Prevent restores
– Recovery fork
• FirstLSN
• LastLSN
• DatabaseBackupLSN
– If point in time is not available
• Source check
– Instance
– Database
– Backup
• Instance
• Database
• Time frame
• Alternate backup file locations
Restore: Preparation
• Target check
– Instance
– Database
– Disk space
Read Backup file content
• SQLPS 2014: No Get-SQLBackupFileInfo
• Wrap it into a powershell function using …
SMO
Get-SQLBackupFileInfo
function Get-SQLBackupFileInfo {
param ([string[]]$BackupFile,
[string]$SQLServer='servermissing',
[string]$DbName
)
$tmpout = @()
$sqlsvr = New-Object -TypeName Microsoft.SQLServer.Management.Smo.Server($SQLServer)
$restore = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Restore
$devicetype = [Microsoft.SqlServer.Management.Smo.DeviceType]::File
foreach ($file in $BackupFile){
$restoredevice = New-Object -TypeName Microsoft.SQLServer.Management.Smo.BackupDeviceItem($file,$devicetype)
$restore.Devices.add($restoredevice)
$errcnt=0
try{
$Headers = $restore.ReadBackupHeader($sqlsvr) | where-object { $_.DatabaseName -eq $DbName }
$Headers | Select @{n='BackupFileName';e={$file}}, *
}
catch [System.Exception]{
$errcnt = 1
}
finally {
if ($errcnt -ne 1){
$tmpout += $file
}
$errcnt = 0
}
$restore.Devices.remove($restoredevice) | out-null
Remove-Variable restoredevice
}
return
}
Backup fork
$DBBackupInfo.FamilyGUID -eq $LogBackup.FamilyGUID
Loop over LastLSN sequences
$PreviousLogLastLSN = $LogBackup.LastLSN
Check Point-In-Time
foreach ( $BU in $LogBackupInfo ) {
$counter ++
$MaxBackupFinishDate = $("{0:yyyy-MM-dd HH:mm:ss.fff}" -f $BU.BackupFinishDate )
if ( $BU.BackupFinishDate -ge $dtPIT -and $PITFound -eq $false ) {
$MaxBackupFilePointer = $counter
$PITFound = $true
}
else {
write-verbose $('start [{0}] - end [{1}]' -f $("{0:yyyy-MM-dd HH:mm:ss.fff}" -f
$BU.BackupStartDate ), $("{0:yyyy-MM-dd HH:mm:ss.fff}" -f $BU.BackupFinishDate ) )
}
}
if ( $PITFound -eq $false ) {
Write-Error $('Point in Time [{0}] not found in available log backups for database
[{1}] of server [{2}]. Maximum available is [{3}]' -f $PointInTime, $SourceDb,
$SourceServer, $MaxBackupFinishDate )
break
}
PIT
The actual restore
Full Diff Log
Process all collected backup files
• Force target dabase offline
– (Get-SqlDatabase -ServerInstance ‘si' -Name ‘db‘).SetOffline()
• will fail without notification when there are still connections
– $SMOdb.ExecuteNonQuery( $("if exists ( select 1 from sys.databases
where name ='{0}' and state = 0 ) Alter database [{0}] set offline
with rollback immediate ; " -f $TargetDb ) )
• -NoRecovery
• -Checksum
• -RelocateFile $rfl
• -FileNumber $DBBackupInfo.Position
• -ReplaceDatabase
Post restore operations
• Send-MailMessage
• Sp_changedbowner / ALTER AUTHORIZATION
• Resync Logins and SQLUsers
– Naming conventions
– Do not grant missing accounts !
• DBCC CheckDB
Things start coming together
• Put it in a .PS1 file to be used providing
the parameters
Clear-Host
Set-Location $ScriptPath ;
& '.ALZDBA Restore SQL Server database (SQLPS).ps1' -SourceServer ‘S1I1'
-SourceDb 'DB' -TargetServer ‘S2I2' -TargetDb 'DB'-LogRestore
-PointInTimeRestore -PointInTime '2014-05-21 12:00:00'
Thoughts
• Individual execution of restores
• Pipe
• Parallel execution
– Posh Jobs
– Posh Workflows
$DbNames | % { Set-Location $Script:ScriptPath ;
& '.ALZDBA Restore SQL Server database (SQLPS).ps1'
-SourceServer "$SourceServer" -SourceDb "$_"
-TargetServer "$TargetServer" -TargetDb "$_"
-LogRestore -PointInTimeRestore -PointInTime $PointInTime;
}
FF & resources
Session evaluations
Thank you
Thank you
“Education is not to fill a bucket, but lighting a fire."
William Butler Yeats
(Irish prose Writer, Dramatist and Poet. Nobel Prize for Literature in 1923. 1865-1939)
Belgium’s biggest IT PRO Conference

More Related Content

PDF
Learning postgresql
PDF
High-Performance Hibernate - JDK.io 2018
PDF
Cassandra 3.0
PDF
Cassandra 3.0 advanced preview
PDF
Testing Cassandra Guarantees under Diverse Failure Modes with Jepsen
PDF
Create a Database Application Development Environment with Docker
PDF
DATABASE AUTOMATION with Thousands of database, monitoring and backup
PDF
Oracle Database SQL Tuning Concept
Learning postgresql
High-Performance Hibernate - JDK.io 2018
Cassandra 3.0
Cassandra 3.0 advanced preview
Testing Cassandra Guarantees under Diverse Failure Modes with Jepsen
Create a Database Application Development Environment with Docker
DATABASE AUTOMATION with Thousands of database, monitoring and backup
Oracle Database SQL Tuning Concept

What's hot (19)

PPTX
Oracle database 12.2 new features
PPTX
AWR DB performance Data Mining - Collaborate 2015
PDF
Oracle Database Performance Tuning Concept
PDF
GLOC 2014 NEOOUG - Oracle Database 12c New Features
PPT
Intro to ASH
PPT
Direct SGA access without SQL
PPT
Oracle Open World Thursday 230 ashmasters
PDF
REST in Piece - Administration of an Oracle Cluster/Database using REST
PDF
PostgreSQL WAL for DBAs
PDF
Oracle WebLogic Server 12c with Docker
PPTX
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
PDF
How to Avoid Pitfalls in Schema Upgrade with Galera
PDF
Oracle Database Management Basic 1
PPTX
Sql Server 2008 New Programmability Features
PDF
Highload Perf Tuning
PDF
Major features postgres 11
 
PDF
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
PDF
監査ログをもっと身近に!〜統合監査のすすめ〜
PPTX
Oracle Database 12c Release 2 - New Features On Oracle Database Exadata Expr...
Oracle database 12.2 new features
AWR DB performance Data Mining - Collaborate 2015
Oracle Database Performance Tuning Concept
GLOC 2014 NEOOUG - Oracle Database 12c New Features
Intro to ASH
Direct SGA access without SQL
Oracle Open World Thursday 230 ashmasters
REST in Piece - Administration of an Oracle Cluster/Database using REST
PostgreSQL WAL for DBAs
Oracle WebLogic Server 12c with Docker
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
How to Avoid Pitfalls in Schema Upgrade with Galera
Oracle Database Management Basic 1
Sql Server 2008 New Programmability Features
Highload Perf Tuning
Major features postgres 11
 
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
監査ログをもっと身近に!〜統合監査のすすめ〜
Oracle Database 12c Release 2 - New Features On Oracle Database Exadata Expr...
Ad

Similar to SQL Track: Restoring databases with powershell (20)

PDF
Migrate database to Exadata using RMAN duplicate
PDF
Get database properties using power shell in sql server 2008 techrepublic
PPT
Desired state-configuration-ravikanth-august-2013-vtc india
PPTX
Unbreakable SharePoint 2016 with SQL Server 2016 Always On Availability groups
PDF
Overview of Oracle database12c for developers
PDF
An Approach to Sql tuning - Part 1
PDF
DevOps Meetup ansible
PDF
Oracle10g New Features I
PDF
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
PDF
Unbreakable Sharepoint 2016 With SQL Server 2016 availability groups
PPT
07 Using Oracle-Supported Package in Application Development
PPT
Oracle SQL Tuning
PPTX
SQL Server 2014 Backup to Azure - SQL Saturday CR 2015
PDF
PowerUpSQL - 2018 Blackhat USA Arsenal Presentation
PDF
Owning time series with team apache Strata San Jose 2015
PPTX
Copy Data Management for the DBA
PPTX
Convert single instance to RAC
PPTX
AUSPC 2013 - Business Continuity Management in SharePoint
PPT
Oracle Instance Architecture.ppt
PPTX
Ansible: How to Get More Sleep and Require Less Coffee
Migrate database to Exadata using RMAN duplicate
Get database properties using power shell in sql server 2008 techrepublic
Desired state-configuration-ravikanth-august-2013-vtc india
Unbreakable SharePoint 2016 with SQL Server 2016 Always On Availability groups
Overview of Oracle database12c for developers
An Approach to Sql tuning - Part 1
DevOps Meetup ansible
Oracle10g New Features I
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
Unbreakable Sharepoint 2016 With SQL Server 2016 availability groups
07 Using Oracle-Supported Package in Application Development
Oracle SQL Tuning
SQL Server 2014 Backup to Azure - SQL Saturday CR 2015
PowerUpSQL - 2018 Blackhat USA Arsenal Presentation
Owning time series with team apache Strata San Jose 2015
Copy Data Management for the DBA
Convert single instance to RAC
AUSPC 2013 - Business Continuity Management in SharePoint
Oracle Instance Architecture.ppt
Ansible: How to Get More Sleep and Require Less Coffee
Ad

More from ITProceed (20)

PDF
ITPROCEED_WorkplaceMobility_Windows 10 in the enterprise
PDF
ITPROCEED_TransformTheDatacenter_ten most common mistakes when deploying adfs...
PPTX
The Internet of your things by Jan Tielens
PPTX
Optimal Azure Database Development by Karel Coenye
PPTX
Azure SQL DB V12 at your service by Pieter Vanhove
PPTX
Azure stream analytics by Nico Jacobs
PPTX
ITPROCEED_WorkplaceMobility_Delivering applications with Azure RemoteApp
PPTX
ITPROCEED_TransformTheDatacenter_Automate yourself service management like a ...
PDF
ITPROCEED_WorkplaceMobility_Creating a seamless experience with ue v and wind...
PDF
ITPROCEED_WorkplaceMobility_Delivering traditional File Server Workloads in a...
PDF
ITPROCEED2015_WorkplaceMobility_Configuration Manager 2012’s latest Service P...
PPTX
Office Track: Information Protection and Control in Exchange Online/On Premis...
PPTX
Office Track: Exchange 2013 in the real world - Michael Van Horenbeeck
PDF
Office Track: SharePoint Online Migration - Asses, Prepare, Migrate & Support...
PPTX
Office Track: Lync & Skype Federation v2 Deep Dive - Johan Delimon
PPTX
Office Track: Lync in a VDI Infrastructure - Ruben Nauwelaers & Wim Borgers
PPTX
Office Track: SharePoint Apps for the IT Pro - Thomas Vochten
PDF
SQL Track: Get more out of your data visualizations
PPTX
SQL Track: SQL Server unleashed meet SQL Server's extreme sides
PPTX
SQL Track: In Memory OLTP in SQL Server
ITPROCEED_WorkplaceMobility_Windows 10 in the enterprise
ITPROCEED_TransformTheDatacenter_ten most common mistakes when deploying adfs...
The Internet of your things by Jan Tielens
Optimal Azure Database Development by Karel Coenye
Azure SQL DB V12 at your service by Pieter Vanhove
Azure stream analytics by Nico Jacobs
ITPROCEED_WorkplaceMobility_Delivering applications with Azure RemoteApp
ITPROCEED_TransformTheDatacenter_Automate yourself service management like a ...
ITPROCEED_WorkplaceMobility_Creating a seamless experience with ue v and wind...
ITPROCEED_WorkplaceMobility_Delivering traditional File Server Workloads in a...
ITPROCEED2015_WorkplaceMobility_Configuration Manager 2012’s latest Service P...
Office Track: Information Protection and Control in Exchange Online/On Premis...
Office Track: Exchange 2013 in the real world - Michael Van Horenbeeck
Office Track: SharePoint Online Migration - Asses, Prepare, Migrate & Support...
Office Track: Lync & Skype Federation v2 Deep Dive - Johan Delimon
Office Track: Lync in a VDI Infrastructure - Ruben Nauwelaers & Wim Borgers
Office Track: SharePoint Apps for the IT Pro - Thomas Vochten
SQL Track: Get more out of your data visualizations
SQL Track: SQL Server unleashed meet SQL Server's extreme sides
SQL Track: In Memory OLTP in SQL Server

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Electronic commerce courselecture one. Pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation theory and applications.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Spectroscopy.pptx food analysis technology
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Understanding_Digital_Forensics_Presentation.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Per capita expenditure prediction using model stacking based on satellite ima...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Electronic commerce courselecture one. Pdf
Big Data Technologies - Introduction.pptx
Machine learning based COVID-19 study performance prediction
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Approach and Philosophy of On baking technology
20250228 LYD VKU AI Blended-Learning.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation theory and applications.pdf
Unlocking AI with Model Context Protocol (MCP)
Spectroscopy.pptx food analysis technology
Dropbox Q2 2025 Financial Results & Investor Presentation
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Understanding_Digital_Forensics_Presentation.pptx

SQL Track: Restoring databases with powershell

  • 1. Restoring SQL Server databases using Powershell Johan Bijnens #ITPROceed
  • 2. Johan Bijnens • Who am I ? – SQLServerCentral.com – @alzdba • CERA – KBC Bank (1988 – 1999) – Assembler / Cobol / APS / SAS / JCL – VSAM / IMSdb / DB2 • ALZ – Ugine&ALZ – Arcelor – ArcelorMittal - – PLI / Cobol / VBS / VB.net – DB2 – SQLServer (7.0 – 2000 – 2005 – 2008 R2 – 2012 - 2014) – Oracle / Powershell
  • 3. Restoring Databases using . • Build plan of approach to structured point in time restores of databases ( e.g. from Production to QA ) using Powershell as an easy helper tool to ensure all steps are being performed. Think Know
  • 4. Backup • Backup: • Minimise data loss in case of disaster • RPO: Recovery Point Objective = Data loss • RTO: Recovery Time Objective = Down time • RSO: Recovery Service Objective = Disaster infrastructure needed • SQL server database backup : – Full: Copy of all active pages in your database into a file. – Differential: Copy of all modified pages since the last Full backup – Log: Copy of all database transactions since the last Log backup – Checksum ( Exec sp_configure ‘backup checksum default’,1; Reconfigure ) • What good is a backup if you cannot restore it ?
  • 5. The Setup • # SQLServer instances have been set up to support the different QA environments • Every instance already has the databases pre-configured, SQLUser accounts in place, windows domain groups, … • Segregation of duties: – different passwords – Different windows domain groups • Naming conventions help out to make it all work smooth. • Keep It Simple & Stupid works !
  • 6. The Setup • Dev/QA teams: – Have databases for which they are responsible – Request ad-hoc data refresh for a given database for which they have responsibility. – point-in-time restore can be requested – Approval by team leader
  • 7. SQL Server and Powershell • SQLPs: – Powershell integration provided by Microsoft SQL Server since 2008 – SQL 2012 provides module SQLPs – SQL 2014 enhanced / extended SQLPs – SQLAgent integration (job step) - http://sqlpsx.codeplex.com/
  • 8. SMO vs Powershell ? • SQL Server Management Objects (SMO) – SSMS – object hierarchy and the relationships – http://msdn.microsoft.com/en- us/library/ms162209.aspx – Namespaces for different areas of functionality within SMO. – Still needed in case SQLPs • doesn’t cover the topic • cannot handle it
  • 9. SMO vs Powershell ? • SMO namespaces: – http://msdn.microsoft.com/en-us/library/ms162233.aspx Class Function Microsoft.SqlServer.Management.Smo Contains instance classes, utility classes, and enumerations Microsoft.SqlServer.Management.Common Replication Management Objects (RMO) and SMO, such as connection classes. Microsoft.SqlServer.Management.Smo.Agent SQL Server Agent. Microsoft.SqlServer.Management.Smo.Wmi WMI Provider. Microsoft.SqlServer.Management.Smo.RegisteredServers Registered Server. (SSMS) Microsoft.SqlServer.Management.Smo.Mail Database Mail. Microsoft.SqlServer.Management.Smo.Broker Service Broker.
  • 10. SMO vs Powershell ? • SQLPs: – 46 Cmdlets that facilitate functionality – Powershell programmers will be able to recognize parallels – Discovery / get-help get-command -module sqlps | sort noun, verb | ft -autosize
  • 11. get-command -module sqlps | sort noun, verb | Select Noun, Name| ft -autosize Noun Name PolicyEvaluation Invoke-PolicyEvaluation SqlAlwaysOn Disable-SqlAlwaysOn Enable-SqlAlwaysOn SqlAuthenticationMode Set-SqlAuthenticationMode SqlAvailabilityDatabase Add-SqlAvailabilityDatabase Remove-SqlAvailabilityDatabase Resume-SqlAvailabilityDatabase Suspend-SqlAvailabilityDatabase SqlAvailabilityGroup Join-SqlAvailabilityGroup New-SqlAvailabilityGroup Remove-SqlAvailabilityGroup Set-SqlAvailabilityGroup Switch-SqlAvailabilityGroup Test-SqlAvailabilityGroup SqlAvailabilityGroupListener New-SqlAvailabilityGroupListener Set-SqlAvailabilityGroupListener SqlAvailabilityGroupListenerStaticIp Add-SqlAvailabilityGroupListenerStaticIp SqlAvailabilityReplica New-SqlAvailabilityReplica Remove-SqlAvailabilityReplica Set-SqlAvailabilityReplica Test-SqlAvailabilityReplica SqlBackupEncryptionOption New-SqlBackupEncryptionOption Sqlcmd Invoke-Sqlcmd Noun Name SqlCredential Get-SqlCredential New-SqlCredential Remove-SqlCredential Set-SqlCredential SqlDatabase Backup-SqlDatabase Get-SqlDatabase Restore-SqlDatabase SqlDatabaseReplicaState Test-SqlDatabaseReplicaState SqlFirewallRule Add-SqlFirewallRule Remove-SqlFirewallRule SqlHADREndpoint New-SqlHADREndpoint Set-SqlHADREndpoint SqlInstance Get-SqlInstance Start-SqlInstance Stop-SqlInstance SqlName Decode-SqlName Encode-SqlName SqlNetworkConfiguration Set-SqlNetworkConfiguration SqlSmartAdmin Get-SqlSmartAdmin Set-SqlSmartAdmin Test-SqlSmartAdmin UrnToPath Convert-UrnToPath
  • 12. Basic functions with regards to recovery • Get-help Restore-SQLDatabase • Restore-SqlDatabase -ServerInstance ‘serverinstance’ -Database ‘Db_Restored’ -BackupFile ‘J:MSSQL12.instanceMSSQLBackupDbFull.bak’ • Done! Right ?
  • 13. Restoring is just a part • Security – Sqlusers / passwords – Domain accounts – Domain groups • Integrity – Detect physical / logical errors ASAP – Backup corruption – Restore corruption
  • 14. Restore: Preparation • Prevent restores – Recovery fork • FirstLSN • LastLSN • DatabaseBackupLSN – If point in time is not available • Source check – Instance – Database – Backup • Instance • Database • Time frame • Alternate backup file locations
  • 15. Restore: Preparation • Target check – Instance – Database – Disk space
  • 16. Read Backup file content • SQLPS 2014: No Get-SQLBackupFileInfo • Wrap it into a powershell function using … SMO
  • 17. Get-SQLBackupFileInfo function Get-SQLBackupFileInfo { param ([string[]]$BackupFile, [string]$SQLServer='servermissing', [string]$DbName ) $tmpout = @() $sqlsvr = New-Object -TypeName Microsoft.SQLServer.Management.Smo.Server($SQLServer) $restore = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Restore $devicetype = [Microsoft.SqlServer.Management.Smo.DeviceType]::File foreach ($file in $BackupFile){ $restoredevice = New-Object -TypeName Microsoft.SQLServer.Management.Smo.BackupDeviceItem($file,$devicetype) $restore.Devices.add($restoredevice) $errcnt=0 try{ $Headers = $restore.ReadBackupHeader($sqlsvr) | where-object { $_.DatabaseName -eq $DbName } $Headers | Select @{n='BackupFileName';e={$file}}, * } catch [System.Exception]{ $errcnt = 1 } finally { if ($errcnt -ne 1){ $tmpout += $file } $errcnt = 0 } $restore.Devices.remove($restoredevice) | out-null Remove-Variable restoredevice } return }
  • 18. Backup fork $DBBackupInfo.FamilyGUID -eq $LogBackup.FamilyGUID Loop over LastLSN sequences $PreviousLogLastLSN = $LogBackup.LastLSN
  • 19. Check Point-In-Time foreach ( $BU in $LogBackupInfo ) { $counter ++ $MaxBackupFinishDate = $("{0:yyyy-MM-dd HH:mm:ss.fff}" -f $BU.BackupFinishDate ) if ( $BU.BackupFinishDate -ge $dtPIT -and $PITFound -eq $false ) { $MaxBackupFilePointer = $counter $PITFound = $true } else { write-verbose $('start [{0}] - end [{1}]' -f $("{0:yyyy-MM-dd HH:mm:ss.fff}" -f $BU.BackupStartDate ), $("{0:yyyy-MM-dd HH:mm:ss.fff}" -f $BU.BackupFinishDate ) ) } } if ( $PITFound -eq $false ) { Write-Error $('Point in Time [{0}] not found in available log backups for database [{1}] of server [{2}]. Maximum available is [{3}]' -f $PointInTime, $SourceDb, $SourceServer, $MaxBackupFinishDate ) break } PIT
  • 21. Process all collected backup files • Force target dabase offline – (Get-SqlDatabase -ServerInstance ‘si' -Name ‘db‘).SetOffline() • will fail without notification when there are still connections – $SMOdb.ExecuteNonQuery( $("if exists ( select 1 from sys.databases where name ='{0}' and state = 0 ) Alter database [{0}] set offline with rollback immediate ; " -f $TargetDb ) ) • -NoRecovery • -Checksum • -RelocateFile $rfl • -FileNumber $DBBackupInfo.Position • -ReplaceDatabase
  • 22. Post restore operations • Send-MailMessage • Sp_changedbowner / ALTER AUTHORIZATION • Resync Logins and SQLUsers – Naming conventions – Do not grant missing accounts ! • DBCC CheckDB
  • 23. Things start coming together • Put it in a .PS1 file to be used providing the parameters Clear-Host Set-Location $ScriptPath ; & '.ALZDBA Restore SQL Server database (SQLPS).ps1' -SourceServer ‘S1I1' -SourceDb 'DB' -TargetServer ‘S2I2' -TargetDb 'DB'-LogRestore -PointInTimeRestore -PointInTime '2014-05-21 12:00:00'
  • 24. Thoughts • Individual execution of restores • Pipe • Parallel execution – Posh Jobs – Posh Workflows $DbNames | % { Set-Location $Script:ScriptPath ; & '.ALZDBA Restore SQL Server database (SQLPS).ps1' -SourceServer "$SourceServer" -SourceDb "$_" -TargetServer "$TargetServer" -TargetDb "$_" -LogRestore -PointInTimeRestore -PointInTime $PointInTime; }
  • 28. Thank you “Education is not to fill a bucket, but lighting a fire." William Butler Yeats (Irish prose Writer, Dramatist and Poet. Nobel Prize for Literature in 1923. 1865-1939)
  • 29. Belgium’s biggest IT PRO Conference