Mariusz, Gorzoch tech Blog

SQL backup from PowerShell

with one comment

Today I came against a problem of ‘how to perform backup of database from PowerShell’ script. If you start goggling around it then you will find that there are some extensions with are part of SQL 2012 or feature packs with you can add to your installation… but guess what : I just want to do simple backup without putting too much effort and by the way my server is running SQL Express 2008 R2. Lucky this can be resolved be good old ADO. Please find script to do that below:

# Create and open a database connection
$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=.;database=db;Integrated Security=sspi"
#Create a command object
$tStamp = Get-Date -format yyyy_MM_dd_HHmmss
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = "backup database db to disk = ‘c:\backupFolder\db_"+$tStamp+".bak’ with copy_only"
#Execute the Command
$sqlReader = $sqlCommand.ExecuteScalar()
# Close the database connection

Done it and couldn’t be easier


Written by Mariusz Gorzoch

9 January 2014 at 12:23

Posted in Powershell, SQL

One Response

Subscribe to comments with RSS.

  1. I think, it actually can be easier if you use SMO with powershell..


    26 February 2014 at 16:37

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: