Skip to content

Export-HyperVVM

Hyper-V: Exports a virtual machine to a specified path

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

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

    [PSCredential]$Credential,

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

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

    [ValidateSet('CaptureCrashConsistentState', 'CaptureSavedState', 'CaptureDataConsistentState')]
    [string]$CaptureLiveState = "CaptureCrashConsistentState"
)

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

        $vm = Get-VM @params | Where-Object { $_.Name -eq $Name -or $_.Id -eq $Name }

        if (-not $vm) {
            throw "Virtual machine '$Name' not found on '$ComputerName'."
        }

        if (-not (Test-Path -Path $Path)) {
            New-Item -ItemType Directory -Path $Path -Force | Out-Null
        }

        Export-VM -VM $vm -Path $Path -CaptureLiveState $CaptureLiveState -ErrorAction Stop

        $result = [PSCustomObject]@{
            VMName           = $vm.Name
            ExportPath       = $Path
            CaptureLiveState = $CaptureLiveState
            Action           = "VMExported"
            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 name or ID of the virtual machine to export.

Specifies the directory path where the virtual machine will be exported.

Optional. Specifies how to handle the virtual machine's live state (CaptureCrashConsistentState, CaptureSavedState, CaptureDataConsistentState).

An interactive directory of PowerShell scripts.