Skip to content

Instantly share code, notes, and snippets.

@PCfromDC
Last active January 29, 2016 02:18
Show Gist options
  • Save PCfromDC/3c67356f6cea4768a2c8 to your computer and use it in GitHub Desktop.
Save PCfromDC/3c67356f6cea4768a2c8 to your computer and use it in GitHub Desktop.
Back Up SQL User Databases Using PowerShell
Import-Module SQLPS -DisableNameChecking -EA 0
# Get the current date
$date = Get-Date -Format yyyyMMdd
# Set location of backup files
$backupPath = "J:\Backups"
$sqlInstance = $env:COMPUTERNAME
# Grab the Databases
$dbNames = Get-ChildItem "SQLSERVER:\SQL\$sqlInstance\DEFAULT\Databases" | Select Name
# Backup the Databases
foreach ($dbName in $dbNames) {
$db = $dbName.Name.ToString()
$bakfile = $backupPath + "\" + $db + "_" + $date + ".bak"
Write-Verbose("Backing up Database: $db") -Verbose
$query1 = "BACKUP DATABASE $db TO DISK=N'$bakfile' WITH INIT"
Invoke-Sqlcmd -SuppressProviderContextWarning -Query $query1 -QueryTimeout 600
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment