Skip to content

Import-HyperVVM

Hyper-V: Imports a virtual machine from a configuration file

#Requires -Version 5.1
#Requires -Modules Hyper-V

[CmdletBinding()]
Param (
    [string]$ComputerName = "localhost",

    [PSCredential]$Credential,

    [Parameter(Mandatory = $true)]
    [string]$Path,

    [Parameter(ParameterSetName = "Register")]
    [switch]$Register,

    [Parameter(ParameterSetName = "Copy")]
    [switch]$Copy,

    [Parameter(ParameterSetName = "Copy")]
    [switch]$GenerateNewId,

    [string]$VhdDestinationPath
)

Process {
    try {
        $params = @{
            'Path'         = $Path
            'ComputerName' = $ComputerName
            'ErrorAction'  = 'Stop'
        }
        if ($Credential) { $params.Add('Credential', $Credential) }

        if ($Register) {
            $params.Add('Register', $true)
        }
        else {
            if ($GenerateNewId) { $params.Add('GenerateNewId', $true) }
            if ($VhdDestinationPath) { $params.Add('VhdDestinationPath', $VhdDestinationPath) }
        }

        $vm = Import-VM @params

        $result = [PSCustomObject]@{
            Name         = $vm.Name
            Id           = $vm.Id
            Path         = $vm.Path
            Action       = "VirtualMachineImported"
            Status       = "Success"
            Timestamp    = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }

        Write-Output $result
    }
    catch {
        throw
    }
}

Specifies the name of the Hyper-V host. Defaults to the local machine.

Specifies the credentials to use for the remote connection.

Specifies the path to the virtual machine configuration file.

Off

If set, registers the virtual machine in-place using its existing ID and file locations.

Off

If set, copies the virtual machine files to the host's default locations.

Off

If set, generates a new unique identifier for the imported virtual machine.

Optional. Specifies the folder to which the VHD files should be copied.

An interactive directory of PowerShell scripts.