Backup

Stopping All Running Virtual Machines (Hyper-V)

So, a good friend and fellow MVP asked me for a script to shut down all running virtual machines on a server so she could do cold backups of them. This seemed like a perfectly reasonable request, and my first thought was “Well, this gets really obvious and easy in Windows Server 8” since we have a full set of Hyper-V cmdlets there. But then I sort of remembered doing something like this before, and hunted around and found this old TechNet Wiki article I wrote over a year ago. It wasn’t a full fledged script, but had all the pieces I needed to put together a simple script to stop all the VMs on the local Hyper-V host:

# This is a simple script to stop all the currently running VMs on the local
# Hyper-V host. It could easily be extended to accept a command line
# argument of the name of a remote Hyper-V hosts or a list of hosts into an array

$VMs = Get-WmiObject MSVM_ComputerSystem -computer "." -namespace "root\virtualization"
foreach ($vm in $VMs) {
   if ( $vm.name -ne $vm.elementname ) {
      # skip the parent's name
      if ( $vm.EnabledState -eq 2 ) {
         # If the VM is running
         $shutdown = Get-WmiObject MSVM_ComputerSystem `
                        -namespace "root\virtualization" `
                        –query “Associators of {$vm} where ResultClass=Msvm_ShutdownComponent”
         $shutdown.iniateShutdown($true,”System Maintenance”)
         sleep 5
      }
   }
}

So, what’s happening in that script? Well, Get-WmiObject grags a list of all the VMs on the local Hyper-V Host (-computer “.”), then we simply loop through the list (skipping host itself ($vm.name -ne $vm.elementname), and for each VM that is running ($vm.EnabledState -eq 2), we get a shutdown object for that specific VM and then call the initiateShutdown method on that object.

 

Note that this is a “forced shutdown”, so is equivalent to “shutdown –s –f” at the command line. Some processes may not get politely shutdown. Too bad, so sad. Since we need this to work regardless of what else is happening, that’s a necessary risk.

 

ETA: Wow, this is an old script. Written before we had built-in Hyper-V cmdlets to do this. This still works, and isn't version dependent so far as I know, but I've written updated versions of this a couple of times since. The most recent was 2016, here.  You might want to check that post out. It's a modern, PowerShell v5 version.

Windows Server Backup with PowerShell

Windows Server 2008 R2 added some useful enhancements to the PowerShell snapin that was in Windows Server 2008. But it’s still a pain to use, and a bit hard to get your head around. Here’s a basic PowerShell script to do a backup. There are enough comments in there that it should help you get started.

# -----------------------------------------------------------------
# Script to set a Windows Server Backup policy for a server
#
# Assumes: Volumes C: and D: to backup.
#        : Target - \storageserverserverbackup
#        : Exclusions - D:temp, D:Users*.MP3, D:Users*.WMA
#        : VSS Mode - Full Backup
#        : System State - True
#        : Bare Metal Recovery - True
#        : Schedule - 12:30 PM, 11:00 PM
# Requires: Elevated PowerShell
#         :   (Must be run As Administrator)
#
# Planned Improvements: [minor] Check for elevated priv, error politely if not
#                     : [minor] Check for Server Backup PSSnapin before trying to load
#                     : [major] Accept cmdline parameters
#
# ModHist: 1/31/11 - initial (Charlie Russel)
#        :
#
# With profound thanks to Richard Siddaway, Windows PowerShell MVP
# -----------------------------------------------------------------
# By default, the PSSnapin isn''t loaded automatically, so first load it.
Add-PSSnapin Windows.ServerBackup # will error if already loaded, but continue

# First, create a new empty policy
# Alternately, you can open the existing policy in Edit mode with
#   $BackupPolicy = Get-WBPolicy -edit
$BackupPolicy = New-WBPolicy

# Now,define the parts of it.
# First,let''s do the "source" volumes that will be part of the backup.
# This requires us to first get a list of them, and then parse that list
# to add the ones we want (C: and D:)
# We don''t actually need C:, since we''ll get that as part of Bare Metal Restore,
# but we include it anyway for completeness

$volC = Get-WBVolume -AllVolumes | Where {$_.MountPath -eq "C:"}
$volD = Get-WBVolume -AllVolumes | Where {$_.MountPath -eq "D:"}
$Volumes = $volC,$volD

# Now, add those volumes to the blank policy.
Add-WBVolume -policy $BackupPolicy -volume $Volumes

# If you want to do the entire volume, you don''t need to define any exclusions,
# but if you want to exclude any files or folders, you need to define that exclusion
# and add that to the backup policy you''re building. First, define it. 
$excTEMP = New-WBFileSpec -Filespec D:Temp -exclude
$excWMA = New-WBFileSpec -Filespec "D:Users*.wma" -exclude  # Recursive unless
$excMP3 = New-WBFileSpec -Filespec "D:Users*.mp3" -exclude  # -NonRecursive specified
$FileExclusions = $excTEMP,$excWMA,$excMP3

# and then add that to the policy we''re building
Add-WBFileSpec -policy $BackupPolicy -filespec $FileExclusions

# Define the backup target, this time as a network share.
# For backup to share, you need to create a credential to connect to the remote share.
# This wouldn''t be required for specifying a removable disk.
# You can specify the username here (DOMAINUser) but will be prompted for password
$Cred = Get-Credential exampleuser

# Now, define the target
$Target = New-WBBackupTarget -NetworkPath \StorageServerServerBackup -Credential $Cred

# Add the target to the policy
Add-WBBackupTarget -policy $BackupPolicy -target $Target

# Define the schedule
$sch1 = [datetime]"01/31/2011 12:30:00"
$sch2 = [datetime]"01/31/2011 21:00:00"
Set-WBSchedule -policy $BackupPolicy -schedule $sch1,$sch2

# Set for system state and for bare metal recovery
Add-WBSystemState -policy $BackupPolicy
Add-WBBareMetalRecovery -policy $BackupPolicy

# Finally, set for full VSS Backup
Set-WBVssBackupOptions -policy $BackupPolicy -VssFullBackup

# Finally, we need to SET the policy before it actually takes control
Set-WBPolicy -force -policy $BackupPolicy

# This completes the configuration of the SBS server backup policy
$Server = (hostname).tolower()
" The server $Server now has the following backup configuration: "
""
Get-WBPolicy

Windows Server Backup with PowerShell

Here's a basic Windows PowerShell script configure Windows Server 2008 R2 Backup.

# -----------------------------------------------------------------
# Script to set a Windows Server Backup policy for a server
#
# Assumes: Volumes C: and D: to backup.
#        : Target - \\storageserver\serverbackup
#        : Exclusions - D:\temp, D:\Users\*.MP3, D:\Users\*.WMA
#        : VSS Mode - Full Backup
#        : System State - True
#        : Bare Metal Recovery - True
#        : Schedule - 12:30 PM, 11:00 PM
# Requires: Elevated PowerShell
#         :   (Must be run As Administrator)
#
# Planned Improvements: [minor] Check for elevated priv, error politely if not
#                     : [minor] Check for Server Backup PSSnapin before trying to load
#                     : [major] Accept cmdline parameters
#
# ModHist: 1/31/11 - initial (Charlie Russel)
#        :
#
# With profound thanks to Richard Siddaway, Windows PowerShell MVP
# -----------------------------------------------------------------
 
# By default, the PSSnapin isn't loaded automatically, so first load it.
Add-PSSnapin Windows.ServerBackup # will error if already loaded, but continue
# First, create a new empty policy
# Alternately, you can open the existing policy in Edit mode with
#   $BackupPolicy = Get-WBPolicy -edit
$BackupPolicy = New-WBPolicy
# Now, define the parts of it.
# First, let's do the "source" volumes that will be part of the backup.
# This requires us to first get a list of them, and then parse that list
# to add the ones we want (C: and D:)
# We don't actually need C:, since we'll get that as part of Bare Metal Restore,
# but we include it anyway for completeness
$volC = Get-WBVolume -AllVolumes | Where {$_.MountPath -eq "C:"}
$volD = Get-WBVolume -AllVolumes | Where {$_.MountPath -eq "D:"}
$Volumes = $volC,$volD
# Now, add those volumes to the blank policy.
Add-WBVolume -policy $BackupPolicy -volume $Volumes
# If you want to do the entire volume, you don't need to define any exclusions,
# but if you want to exclude any files or folders, you need to define that exclusion
# and add that to the backup policy you're building. First, define it.?
$excTEMP = New-WBFileSpec -Filespec D:\Temp -exclude
$excWMA = New-WBFileSpec -Filespec "D:\Users\*.wma" -exclude  # Recursive unless
$excMP3 = New-WBFileSpec -Filespec "D:\Users\*.mp3" -exclude  # -NonRecursive specified
$FileExclusions = $excTEMP,$excWMA,$excMP3
# and then add that to the policy we're building
Add-WBFileSpec -policy $BackupPolicy -filespec $FileExclusions
# Define the backup target, this time as a network share.
# For backup to share, you need to create a credential to connect to the remote share.
# This wouldn't be required for specifying a removable disk.
# You can specify the username here (DOMAIN\User) but will be prompted for password
$Cred = Get-Credential example\user
# Now, define the target
$Target = New-WBBackupTarget -NetworkPath \\StorageServer\ServerBackup -Credential $Cred
# Add the target to the policy
Add-WBBackupTarget -policy $BackupPolicy -target $Target
# Define the schedule
$sch1 = [datetime]"01/31/2011 12:30:00"
$sch2 = [datetime]"01/31/2011 21:00:00"
Set-WBSchedule -policy $BackupPolicy -schedule $sch1,$sch2
# Set for system state and for bare metal recovery
Add-WBSystemState -policy $BackupPolicy
Add-WBBareMetalRecovery -policy $BackupPolicy
# Finally, set for full VSS Backup
Set-WBVssBackupOptions -policy $BackupPolicy -VssFullBackup
# Finally, we need to SET the policy before it actually takes control
Set-WBPolicy -force -policy $BackupPolicy
# This completes the configuration of the SBS server backup policy
$Server = (hostname).tolower()
" The server $Server now has the following backup configuration: "
""
Get-WBPolicy