Help making my RestoreDB script better pls?

  • I'm a total noob with posh 🙂 I got it powershell running and then hacked together this script.

    I was following the article about powershell restores (https://www.simple-talk.com/sql/backup-and-recovery/backup-and-restore-sql-server-with-the-sql-server-2012-powershell-cmdlets/).

    I made a script based on this, but I had some further needs not met in the article.

    First, SingleUserMode. Maybe it's just my environment, but restores of our big DB doesn't work without this. Application just keeps making connections.

    Second, I have to perform some actions I've currently figured was easiest done with TSQL. Here I'm just looking at the last restore date.

    In reality, I have to reset passwords, remove/add logins, attach logins to users, sometimes run a special script to change some default settings... Just a few executenonquery type of things.

    I'll also have to add moving the backup file as well or as a separate method/function. Whats it called when you encapsulate in powershell?

    First, if there is a 100% powershell way to do most of these things, I'd love to learn it!

    But I'd also love to learn how one would best run a query with results and without results against a server.

    And that last bit? That's a total hack on displaying the information. Can anyone point to a better way to displaying it?

    cls

    #import SQL Server module

    Import-Module SQLPS -DisableNameChecking

    # Sets context for getting a db reference.

    # I use the reference to change the user access and verify the backup date after the restore

    Set-Location SQLSERVER:\SQL\(server)\(instance)\Databases\(database)

    $dbName = "db"

    $db = Get-Item .

    echo $db.UserAccess

    # The next few lines handle changing the databases user access mode which prevents restoring due to active connections

    # I run this if the db is set to Multiple (it normally is)

    #$db.UserAccess = "Multiple"

    $db.UserAccess = "Single"

    $db.Parent.KillAllProcesses($dbName)

    $db.Alter()

    Restore-SqlDatabase -Database $dbName -BackupFile "(backup path).bak" -ReplaceDatabase

    # Here and below is my TSQL hammer approach to solve the problem of verifing the restore date on the DB we're attempting to restore.

    # I'm sure that this can be done more elegantly within Posh and even using a TSQL query, this has to be a hacky way to display the output of a known schema result.

    cls

    $BackupTimeQuery = @"

    SELECT TOP 1

    destination_database_name As dbname,

    restore_date,

    user_name As RestoredBy

    FROM msdb.dbo.restorehistory RH

    WHERE RH.destination_database_name = '$dbName'

    ORDER BY restore_date DESC;

    "@

    <# Commented out the StringCollection as I don't need it for a single query

    # Setting up StringCollection to use with ExecuteWithResults for multiple queries.

    $sqlQuery = new-object System.Collections.Specialized.StringCollection

    Query to find the most recent backup of the DB being restored.

    $sqlQuery.Add("")

    #>

    $ds = $db.ExecuteWithResults($BackupTimeQuery)

    # Please don't anyone use this as an example, but please do suggest a better way to display multiple fields of a single row returned within Posh.

    Foreach ($t in $ds.Tables)

    {

    Foreach ($r in $t.Rows)

    {

    Foreach ($c in $t.Columns)

    {

    Write-Host $c.ColumnName "=" $r.Item($c)

    }

    }

    }

  • It looks like the basic restore operation is set up fine. It's mainly a question of getting the connections clear before you restrict access to the database. You're going to have to wait for every transaction to roll back during that process. However, I usually don't use single user because it's still possible for another connection to get in front of you. I usually go for restricted because it only lets DBO & sa connections in.

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning

  • Oh, that's good advice with the Single vs Restricted. I've just always used Single and maybe once I had an oddity where I didn't have exclusivity.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply