Backup or Restore SQL Database with Powershell

A cool feature of Powershell is the ability to backup or restore your SQL databases. I used it in a script where I was sending an email with the backup file.

$server = "localhost\SQLEXPRESS"
$database = "DBName"
$filePath = "myDatabase.bak"

# Backup DB
Backup-SqlDatabase -ServerInstance $server -Database $database -BackupFile $filePath -BackupAction Database -ConnectionTimeout 0

# Restore DB
Restore-SqlDatabase -ServerInstance $server -Database $database -BackupFile $filePath -ReplaceDatabase -ConnectionTimeout 0

Find out more on Backup and Restore.