Get a screenshot of an Azure virtual machine programmatically using PowerShell and the Azure REST API
The Boot Diagnostics menu in an Azure virtual machine displays a screenshot of the virtual machine.
This screenshot is availabe in the REST API described here.
https://learn.microsoft.com/rest/api/compute/virtual-machines/retrieve-boot-diagnostics-data
For this to work you must use a POST method and have the "retrieveBootDiagnosticsData/action" permission.
The REST API call returns an object with the URL to the image at an Azure storage URL which can then be downloaded with a web client.
#
Gets the screenshot for the specified virtual machine.
function Get-AzureVirtualMachineScreenshot
{
[CmdletBinding()]
param(
[Parameter()]
[Guid] $SubscriptionIdentifier,
[Parameter()]
[String] $ResourceGroupName,
[Parameter()]
[String] $Name
)
process
{
$response = Invoke-AzRestMethod -Path "/subscriptions/$SubscriptionIdentifier/resourceGroups/$ResourceGroupName/providers/Microsoft.Compute/virtualMachines/$Name/retrieveBootDiagnosticsData?api-version=2022-03-01" -Method POST;
$responseObject = ConvertFrom-Json $response.Content;
$webClient = New-Object System.Net.WebClient;
$screenshot = $webClient.DownloadData($responseObject.consoleScreenshotBlobUri); $webClient.Dispose();
return $screenshot;
}
}
$image = Get-AzureVirtualMachineScreenshot -SubscriptionIdentifier "00000000-0000-0000-0000-000000000000" -ResourceGroupName "ResourceGroupName" -Name "VirtualMachineName"[System.IO.File]::WriteAllBytes("c:\image.jpg", $image);
Comments
Post a Comment