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?
#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
$dbName = "db"
$db = Get-Item .
# 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"
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.
$BackupTimeQuery = @"
SELECT TOP 1
destination_database_name As dbname,
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.
$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)