February 01, 2015

Export Hyper-V Configuration Using PowerShell

When Windows 8 and Windows Server 2012 were released, we also received a new PowerShell module. Within this module are many cmdlets that are designed to make it easy to manage Hyper-V hosts and virtual machines directly from PowerShell. Many of these cmdlets and command line versions of functionality that exists within the graphical Hyper-V manager. But sometimes, even these cmdlets may not meet your needs. As a case in point, consider the Export-VM cmdlet. This cmdlet will export a virtual machine to disk including its disk files and snapshots. In other words, a backup.

Using PowerShell to Export a Hyper-V Configuration

I'm assuming that if you are running Hyper-V in a production environment, then you probably have invested in a backup solution. What I want to demonstrate in this article isn't intended to replace those products, but rather supplement them. If you run a smaller shop, a lab environment, or client Hyper-V on a Windows 8 or later desktop, then this article may be especially handy.

The problem is that when you use the Export-VM cmdlet, you get everything and given the size of the virtual machine hard drives and snapshots, this process may take some time to complete. But perhaps you only want to export the configuration itself? I was working on this problem when I came across someone with this exact issue. He wanted to export the virtual machine configuration so that he could import it later.

The configuration that you see when you run Get-VM or look at a virtual machine settings in Hyper-V Manager are stored in an XML file. The file location is included in the virtual machine object.


The name of the file is the same as the virtual machine's id.


It is pretty easy to get that file with PowerShell.

The file should exist in a sub-folder called Virtual Machines, but sometimes it is not. There is also a possibility there might be multiple XML files, so I do this to get the full file name.



Next, I need to create the destination folder and copy the xml file to it.


In terms of a quick and easy export or backup that's all there is to it. But I'm always thinking about what other requirement someone might have. Assuming you might import the configuration file, it might be helpful to provide a new name for the virtual machine. Or remove hard drive references so that if you import on a different Hyper-V host you don't get ugly errors. Or remove snapshot references. Plus, you most likely want to do this from the comfort of your desktop. So I created a PowerShell function called Export-VMConfiguration.


#requires -version 3.0
 
Function Export-VMConfiguration {
 
<#
.Synopsis
Export Hyper-V configuration file.
.Description
This command will export a Hyper-V virtual machine's configuration file to a new location. You can use this as an alternative to Export-VM which will also export hard drives and snapshots. Sometimes you just want the configuration file.
 
The command has options to provide a new name, as well as remove hard drive or snapshot references. This can be helpful if you plan on importing the configuration later as the basis for a new virtual machine.
 
The path must exist and is relative to the computer. The command will create a subfolder for each virtual machine under this path. The path must be a local, fixed drive. You cannot specify a UNC or shared drive.
.Example
PS C:\> get-vm chi* -computername chi-hvr2 | export-vmconfiguration -path d:\exports -verbose
 
This command will export, or backup, the configuration files for all virtual machines that start with CHI* to a new location on CHI-HVR2.
.Example
PS C:\> Export-VMConfiguration chi-test01 -Path E:\exports -Verbose -NewName CHI-TEST2 -RemoveDrives -RemoveSnapshots
 
This command will get the CHI-TEST01 virtual machine on the local host and export its configuration. The new configuration will reflect a new name and remove existing drives and snapshots.
.Notes
Last Updated: October 13, 2014
Version     : 1.0
 
Learn more:
PowerShell in Depth: An Administrator's Guide (http://www.manning.com/jones6/)
PowerShell Deep Dives (http://manning.com/hicks/)
Learn PowerShell in a Month of Lunches (http://manning.com/jones3/)
Learn PowerShell Toolmaking in a Month of Lunches (http://manning.com/jones4/)
 
 
  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************
 
.Link
Get-VM
Export-VM
#>
 
[cmdletbinding(DefaultParameterSetName="Name")]
 
Param(
[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter the name of a virtual machine",
ValueFromPipeline=$True,
ParameterSetName="Name")]
[alias("vmname")]
[ValidateNotNullorEmpty()]
[string[]]$Name,
[Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$True,
ParameterSetName="VM")]
[Microsoft.HyperV.PowerShell.VirtualMachine[]]$VM,
[Parameter(Mandatory=$True,HelpMessage="Enter the destination path")]
[string]$Path,
[Alias("cn")]
[Parameter(ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullorEmpty()]
[string]$Computername = $env:computername,
[Alias("rename")]
[string]$NewName,
[alias("NoDrives")]
[switch]$RemoveDrives,
[alias("NoSnapshots")]
[switch]$RemoveSnapshots
)
 
Begin {
    Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"  
    Write-Verbose "Using parameter set $($PSCmdlet.ParameterSetName)"
} #begin
 
Process {
 
#create a scriptblock so this can run remotely
$sb = {
[cmdletbinding()]
Param(
[string]$VerbosePreference
)
#$VerbosePreference = "continue"
    if ($using:vm) {
     Write-Verbose "Processing VM: $($using:VM.Name)"
     $myVM = $using:vm
    }
    else {
     Write-Verbose "Processing $using:name"
     #get the virtual machine
     Try {
        $myvm = Get-VM -Name $using:name
     }
     Catch {
        Write-Warning "Failed to find virtual machine $using:name on $($env:computername)"
     }
    } #else
 
    if ($myVM) {
 
    foreach ($v in $myVM) {
        #proceed if we have a virtual machine object
        #create the target configuration path
        $config = dir $v.configurationlocation -filter "$($v.id).xml" -recurse | Select -first 1 -ExpandProperty fullname
        Write-Verbose "Processing configuration file: $config"
        If ($config) {
        
            #define the target path
             #use the New name if specified
            if ($NewName) {
              $vmname = $NewName
            }
            else {
              $vmname = $v.name
            }
            $destination = Join-path $using:path "$vmname\Virtual Machines"
            Write-Verbose "Testing $destination"
            if (-Not (Test-Path -Path $destination)) {
                #create the folder
                Try {
                    Write-Verbose "Creating $destination"
                    New-Item -Path $destination -ItemType directory -ErrorAction stop | Out-Null
                }
                Catch {
                    Throw  
                }
            } #if destination doesn't exist
 
            if (Test-Path -Path $destination ) {
                Write-verbose "Exporting $config to $destination"
                Try {
                    Copy-item $config -destination $destination -errorAction Stop -passthru
                }
                Catch {
                    Throw
                }
                
                #post processing
                Write-Verbose "Post processing"
                $newConfig = Join-Path -Path $destination -ChildPath "$($v.id).xml"
                [xml]$new = Get-Content -path $newConfig
 
                $prop = $new | select-xml -XPath "//properties/name"
                
                #insert a note
                Write-Verbose "Inserting a note"
                $notes = $new.selectNodes("//notes")
                $noteText = @"
Exported $(Get-date) from $($prop.node.innertext)
$($notes[0].InnerText)
"@
                $notes[0].InnerText = $noteText
 
                if ($NewName) {
                    #rename
                    Write-Verbose "Renaming to $Newname"
                    $prop.node.InnerText = $NewName                    
                } #if new name
 
                #remove drives
                if ($RemoveDrives) {
                    Write-Verbose "Removing drive references"
                    $drivenodes = $new | Select-Xml "//*[starts-with(name(),'drive')]"
 
                   foreach ($item in $drivenodes) {
                      $pn = $item.node.parentnode
                      $pn.RemoveChild($item.node) | Out-Null
                    }
 
                } #remove drives
 
                #remove snapshots
                if ($RemoveSnapshots) {
                    Write-Verbose "Removing snapshot references"
                    $snapnodes = $new | Select-Xml "//snapshots"
                    $snapnodes.node.RemoveChild($snapnodes.node.list) | Out-Null
 
                    $pii= $new | Select-Xml "//parent_instance_id"
                    $new.configuration.properties.RemoveChild($pii.node) | Out-Null
 
                } #remove snapshots
                #save revised configuration
                Write-Verbose "Saving XML to $newconfig"
                $new.save($newconfig)
 
            } #if destination verified
        } #If configuration file found
        else {
            Write-Warning "Failed to find a configuration file for $($v.name)"
        }
      } #foreach
    } #if VM
   } #close scriptblock
  
   Invoke-Command -ScriptBlock $sb -ComputerName $Computername -ArgumentList $VerbosePreference  
} #process
 
End {
    Write-Verbose -Message "Ending $($MyInvocation.Mycommand)"
}

No comments:

Post a Comment