How to back up SQL Server databases in all the instances on a server (PowerShell)

Introduction

This PowerShell script will demo how to back up all the SQL Server databases in all the instances on a server.

Scenarios

As some people asked how to back up databases from multiple instances, this sample will demo how to back up all the SQL Server databases in all the instances on a server.

Script

You can use this script in this way:
1. Run Microsoft PowerShell as Administrator

2. Run the script in the form: &Path
For example: & "E:\OneScript\Julie\BackupDBsOnInstances.ps1"

3. Press “Enter” and enter the directory you want to back up them to.

For example: E:\temp
Note: Do not add double quotation marks in the directory.

4. Press “Enter” and we’ll get the following figure:
 

And we will find all the database backups in the directory you specified, just as shown below:

Here are some code snippets for your reference: 

PowerShell
Edit|Remove
$backup = New-Object Microsoft.SqlServer.Management.Smo.Backup 
                   $backup.Action = [Microsoft.SqlServer.Management.Smo.BackupActionType]::Database 
                   $backup.BackupSetName = $dbname + "_backup_" + $date 
                   $backup.Database = $dbname 
                   $backup.MediaDescription = "Disk" 
                   $backup.Devices.AddDevice($directory  + "\" + $i + "_" + $dbname.ToString() + "_" + $date + ".bak", "File") 
                   try 
                   {Write-Progress -Activity "Please wait! Backuping SQL databases... " -Status "Processing:" -CurrentOperation "Currently processing: $db" 
                   $backup.SqlBackup($ins) 
                   Write-Host "$dbname backed up!"} 
                   catch 
                   {$dbname + " backup failed." 
                   $_.Exception.Message}

Prerequisites

SQL Server 2005 /SQL Server 2008/SQL Server 2008 R2/SQL Server 2012 (Enterprise or Developer)

Windows PowerShell 2.0, Windows PowerShell 3.0 or Windows PowerShell 4.0