Skip to content

Instantly share code, notes, and snippets.

@jdhitsolutions
Forked from BenjaminArmstrong/SaveVMBitmap.ps1
Last active November 27, 2020 21:16
Show Gist options
  • Save jdhitsolutions/78d71ceeefb54675a7c53a13ac861780 to your computer and use it in GitHub Desktop.
Save jdhitsolutions/78d71ceeefb54675a7c53a13ac861780 to your computer and use it in GitHub Desktop.
Sample PowerShell script that shows you how to create a .BMP file of the display of a Hyper-V virtual machine.
function Get-VMScreenBMP {
[cmdletbinding()]
Param(
[string]$VMName,
[string]$Computername = $env:computername,
[string]$Path,
[switch]$Passthru
)
$VMMS = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_VirtualSystemManagementService -ComputerName $Computername
$VMCS = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter "ElementName='$($VMName)'" -ComputerName $Computername
# Get the resolution of the screen at the moment
$video = $VMCS.GetRelated("Msvm_VideoHead")
$xResolution = $video.CurrentHorizontalResolution
$yResolution = $video.CurrentVerticalResolution
# Get screenshot
$image = $VMMS.GetVirtualSystemThumbnailImage($VMCS, $xResolution, $yResolution).ImageData
# Transform into bitmap
$BitMap = New-Object System.Drawing.Bitmap -Args $xResolution,$yResolution,Format16bppRgb565
$Rect = New-Object System.Drawing.Rectangle 0,0,$xResolution,$yResolution
$BmpData = $BitMap.LockBits($Rect,"ReadWrite","Format16bppRgb565")
[System.Runtime.InteropServices.Marshal]::Copy($Image, 0, $BmpData.Scan0, $BmpData.Stride*$BmpData.Height)
$BitMap.UnlockBits($BmpData)
$bitmap.Save($path)
If ($Passthru) {
Get-Item $path
}
}
@BenjaminArmstrong
Copy link

BTW - the reason why I am not using the code this way is because this line:

$video = $VMCS.GetRelated("Msvm_VideoHead")

Is quite expensive (it takes about 300ms). So if you are just getting a bitmap once - this is fine. However, if you are calling this repeatedly - you just want to get this information and cache it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment