Skip to content

Instantly share code, notes, and snippets.

@PCfromDC
Last active January 29, 2016 02:26
Show Gist options
  • Save PCfromDC/a519b9157e260147d5a3 to your computer and use it in GitHub Desktop.
Save PCfromDC/a519b9157e260147d5a3 to your computer and use it in GitHub Desktop.
Restore SQL User Databases Using PowerShell
Import-Module SQLPS -DisableNameChecking -EA 0
$backupPath = "J:\Backups" # location of all the .bak files
$sqlInstance = $env:COMPUTERNAME
$files = Get-ChildItem -Path $backupPath -Filter *.bak
foreach ($file in $files) {
$fileName = $file.Name
$dbName = $fileName.Substring(0,($fileName.Length - 13)) # length based off suffix of "_yyyyMMdd.bak" eg: "_20161901.bak"
Write-Verbose ("Restoring $dbName...") -Verbose
Restore-SqlDatabase -ServerInstance $sqlInstance -Database $dbName -BackupFile $file.FullName -RestoreAction Database -ReplaceDatabase
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment