PowerShell Script for Exporting a virtual machine
I need to automate the process of exporting a virtual machine recently – and when I checked around I found that while there are a number of sample scripts out there that show you how to do this (some even on this blog) they are all written in VBScript. As I am now to the stage where PowerShell is my preferred scripting language – I sat down and wrote up this short script:
# Function for handling WMI jobs / return values
Function ProcessResult($result, $successString, $failureString)
{
#Return success if the return value is "0"
if ($result.ReturnValue -eq 0)
{write-host $successString}
#If the return value is not "0" or "4096" then the operation failed
ElseIf ($result.ReturnValue -ne 4096)
{write-host $failureString " Error value:" $result.ReturnValue}
Else
{#Get the job object
$job=[WMI]$result.job
#Provide updates if the jobstate is "3" (starting) or "4" (running)
while ($job.JobState -eq 3 -or $job.JobState -eq 4)
{write-host $job.PercentComplete "% complete"
start-sleep 1
#Refresh the job object
$job=[WMI]$result.job}
#A jobstate of "7" means success
if ($job.JobState -eq 7)
{write-host $successString
return $true}
Else
{write-host $failureString
write-host "ErrorCode:" $job.ErrorCode
write-host "ErrorDescription" $job.ErrorDescription
return $false}
}
}
# Prompt for the Hyper-V Server to use
$HyperVServer = Read-Host "Specify the Hyper-V Server to use (enter '.' for the local computer)"
# Prompt for the virtual machine to use
$VMName = Read-Host "Specify the name of the virtual machine"
# Prompt for the path to export to
$ExportPath = Read-Host "Specify the path to place the exported virtual in"
# Get the management service
$VMMS = gwmi -namespace root\virtualization Msvm_VirtualSystemManagementService -computername $HyperVServer
# Get the virtual machine object
$VM = gwmi MSVM_ComputerSystem -filter "ElementName='$VMName'" -namespace "root\virtualization" -computername $HyperVServer
# Export the virtual machine
$result = $VMMS.ExportVirtualSystem($VM, $true, $ExportPath)
# Check to make sure we succeeded
$exportSucceeded = ProcessResult $result "Virtual machine exported." "Failed to export virtual machine."
Some quick notes to make about this script:
- This script takes a Hyper-V server name, a virtual machine name and an export path – and then performs a full export to the requested location.
- I am using the older (deprecated) ExportVirtualSystem method here – and not ExportVirtualSystemEx (which I really should do). The main reason for this is that while ExportVirtualSystemEx is a lot more powerful than ExportVirtualSystem, ExportVirtualSystem works perfectly fine for this basic use case and is much easier to script.
Cheers,
Ben
Comments
Anonymous
February 21, 2012
i just tried your script 5 minutes ago and it didn't work. FYI, I'm not a programmer but I've been trying to find a way to clone my VMs. So please point out where I did wrong. ThanksAnonymous
February 28, 2012
Hi Ben, A quick note .. we just released a free PowerShell script to automate export of Hyper-V VMs. It's quite an extensive job-based script. We have a download at www.altaro.com/.../free-download-powershell-script-for-hyper-v-export.Anonymous
March 29, 2012
Hi Ben, I am using the following script. This can be executed through task manager by the runas command prompt: powershell.exe -noexit <Path to .ps1> • Shutdown VM (Gracefully) • Export VM to a network share • Copy from a network share to the local drive on HyperV Host • Import VM into HyperV Host • Start imported VM Following is the code to make this happen. Note that there are 2 “VMName” folders, this is done so the first is a dummy folder that allows RoboCopy to copy all the contents necessary for import. We must create the VMName folder previous to executing these for the first time, following the first time it will not be an issue. Get-VM -vm VMName | invoke-vmshutdown -force Export-VM -VM VMName -Path "\ShareNameVMName" -CopyState -Wait robocopy "\ShareNameVMName" "LocalDriveLocation" /E Import-VM -Path "PathOfImport" -Server HyperVServerImportedOn Start-VM -vm VMName I hope this helps someone else that needs to do the same. We need to export, copy, then import, then start so we know that there is a working backup of the server.Anonymous
April 07, 2013
Hi Can you please suggest that how to use above scripts manually :(Anonymous
April 09, 2015
Prasad, To learn using the powershell scripts and easily understand the way Ben have written it try to learn the basics. For example try this guide www.veeam.com/wp-powershell-newbies-start-powershell.html or u try to look through technet resources.Anonymous
August 29, 2016
I blog often and I seriously appreciate your information. This article has really peaked my interest. I'm going to book mark your website and keep checking for new details about once a week. I opted in for your RSS feed as well.