You might have noticed over the last 26 days that I seem to prefer using the long form of PowerShell backups over the more concise cmdlet versions.
There’s real reason for this, as they’re all building up the same T-SQL BACKUP
statements at the end of the day. However, I find that when automating things, building up a backup one option at a time like:
$Restore.Replace=$True $Restore.NoRecovery = $False
This gives me very easy control of what gets passed in to my backup or restore.:
if ($x -eq y){ $Restore.Replace=$True }else{ $Restore.Replace=$False }
and so on for all the parameters you might want to add.
But with the newer Restore-SQLDatabase
cmdlet you can’t use:
if ($x -eq y){ $RecoveryOption = $True }else{ $RecoveryOption = $False } Restore-SQLDatabase -Database $DBName -BackupFile $backupfile -NoRecovery $RecoveryOption
As -NoRecovery
is a switch, not a parameter. This means that just specifying the switch turns the feature on or off, there is no actual parameter to pass through to it. This can be a bit limiting when you’re wanting complete control within a flexible set of scripts.
I find the new cmdlets are much easier when you just want to quickly back something up from the command line. Today I used this 2 line to quickly backup all the databases on a dev/test server before we tried something destructive:
cd SQLSERVER:\SQL\DEVBOX1\DEFAULT\DATABASES ls|%{$_|Backup-SQLDatabase}
Much simpler and quicker to type than anything else I can think of!
(Just in case you can’t read what is a great example of bad code, I’m making use of a couple of shortcuts in PowerShell:
ls is a system alias for Get-ChildItem, which coming from a Unix background I tend to use naturally. And % is an alias for foreach, and doing that on a collection of system objects defaults to stepping through the objects in the collection loading $_ on each iteration. Plus PowerShell doesn’t mind about missing spaces if things aren’t ambiguous. This type of code is great for one offs when you just want to do something quickly, but not something you ever want leave in proper scripts or functions, and is not fun to discover when debugging as it probably means shortcuts were also taken elsewhere!)
So to answer the original question, it’s just down to a personal preference, and using the right tool at the right time.
This post is part of a series posted between 1st September 2013 and 3rd October 2013, an index for the series is available here.
Mats Gårdstad Friberg
Just a note. You can have variables for switches. Just add a colon.
if ($x -eq y){
$RecoveryOption = $True
}else{
$RecoveryOption = $False
}
Restore-SQLDatabase -Database $DBName -BackupFile $backupfile –NoRecovery:$RecoveryOption
Stuart Moore
Thank you for that, always good to start the day learning something new 🙂
Cheers
Stuart