File: get_vm_status.ps1

package info (click to toggle)
vagrant 2.2.14%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 9,800 kB
  • sloc: ruby: 97,301; sh: 375; makefile: 16; lisp: 1
file content (49 lines) | stat: -rw-r--r-- 1,656 bytes parent folder | download | duplicates (4)
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
45
46
47
48
49
#Requires -Modules VagrantMessages

param(
    [Parameter(Mandatory=$true)]
    [string]$VmId
)

# Make sure the exception type is loaded
try
{
    # Microsoft.HyperV.PowerShell is present on all versions of Windows with HyperV
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.HyperV.PowerShell, Culture=neutral, PublicKeyToken=31bf3856ad364e35')
    # Microsoft.HyperV.PowerShell.Objects is only present on Windows >= 10.0, so this will fail, and we ignore it since the needed exception
    # type was loaded in Microsoft.HyperV.PowerShell
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.HyperV.PowerShell.Objects, Culture=neutral, PublicKeyToken=31bf3856ad364e35')
} catch {
  # Empty catch ok, since if we didn't load the types, we will fail in the next block
}

$VmmsPath = if ([environment]::Is64BitProcess) { "$($env:SystemRoot)\System32\vmms.exe" } else { "$($env:SystemRoot)\Sysnative\vmms.exe" }
$HyperVVersion = [version](Get-Item $VmmsPath).VersionInfo.ProductVersion

if($HyperVVersion -lt ([version]'10.0')) {
  $ExceptionType = [Microsoft.HyperV.PowerShell.VirtualizationOperationFailedException]
} else {
  $ExceptionType = [Microsoft.HyperV.PowerShell.VirtualizationException]
}
try {
    $VM = Hyper-V\Get-VM -Id $VmId -ErrorAction "Stop"
    $State = $VM.state
    $Status = $VM.status
} catch [Exception] {
    if($_.Exception.GetType() -eq $ExceptionType)
    {
        $State = "not_created"
        $Status = $State
    }
    else
    {
        throw;
    }
}

$resultHash = @{
    state = "$State"
    status = "$Status"
}
$result = ConvertTo-Json $resultHash
Write-OutputMessage $result