Import-VMsFromFolder – Batch import VMs from folder in Hyper-V!

Ever needed to batch import VMs in Hyper-V based on a folder path? Here is the PowerShell solution for you!
(with some built-in error handling)

Disclaimer: This script is provided ”AS IS” with no warranties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<#
.Synopsis
   Import VMs to Hyper-V from path.
.EXAMPLE
   Import-VMsFromFolder -Path 'D:\VMs\Virtual Machines'
#>
 
function Import-VMsFromFolder
{
    [CmdletBinding()]
    Param
    (
        # Specify VM Path.
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $Path
    )
 
    $VmConfigFiles = (Get-ChildItem -Path $Path -Filter *.xml).FullName    
    $ExistingVMs = (Get-VM).Name
 
    foreach ($VmConfigFile in $VmConfigFiles) {
 
        [xml]$VMXML = Get-Content $VmConfigFile
        $SelectedVM = $VMXML.configuration.properties.name.'#Text'
 
        if ($ExistingVMs -contains $SelectedVM) {
            Write "$SelectedVM - Already Imported"
        } 
            else {
                Write "$SelectedVM : Selecting from $path"
                $VMInfo = Compare-VM -Path $VmConfigFile
 
                if ($VMInfo.Incompatibilities) {
                    Write-Error "$SelectedVM - IMPORTRESULT: NOT IMPORTED : $($VMInfo.Incompatibilities.message)"
                } 
                    else {
                        Import-VM -Path $VmConfigFile -Verbose
                    }
            }      
    }
 
}
This entry was posted in Hyper-V, Powershell. Bookmark the permalink.

Kommentera

E-postadressen publiceras inte. Obligatoriska fält är märkta *

*


5 + = sex

24 279 Spam Comments Blocked so far by Spam Free Wordpress

Följande HTML-taggar och attribut är tillåtna: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>