Skip to content

Instantly share code, notes, and snippets.

Created September 19, 2022 16:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Azure Virtual Desktop - Behind the senes: Log Session Host information each minute to log analytics
"bindings": [
"name": "Timer",
"schedule": "*/60 * * * * *",
"direction": "in",
"type": "timerTrigger"
# Azure Functions profile.ps1
# Authenticate with Azure PowerShell using MSI.
# Remove this if you are not planning on using MSI or Azure PowerShell.
if ($env:MSI_SECRET) {
Disable-AzContextAutosave -Scope Process | Out-Null
Connect-AzAccount -Identity
# This file enables modules to be automatically managed by the Functions service.
# See for additional information.
# For latest supported version, go to ''.
# To use the Az module in your function app, please uncomment the line below.
# 'Az' = '8.*'
'Az.Accounts' = '2.10.0'
'Az.DesktopVirtualization' = '3.1.1'
# Use the script with an Azure function. The Azure function must have a managed identity (System).
# Give the managed identity read access to the resource group containing the host pools (or on the pools themselves).
# Additionally, the managed identity needs read access to key vault secrets containing the WorkspaceId and WorkspaceKey.
# Create both secrets with the information about the log analytics workspace. Reference both secrets in the appsettings of the function app:
# WorkspaceId=@Microsoft.KeyVault(SecretUri= and WorkspaceKey=@Microsoft.KeyVault(SecretUri=
# Input bindings are passed in via param block.
# Get the current universal time in the default string format.
$currentUTCtime = (Get-Date).ToUniversalTime()
# The 'IsPastDue' property is 'true' when the current function invocation is later than scheduled.
if ($Timer.IsPastDue) {
Write-Host "PowerShell timer is running late!"
# Write an information log with the current time.
Write-Host "PowerShell timer trigger function ran! TIME: $currentUTCtime"
# Variables
$ResourceGroup="WVD.Design2" # works on all pools in the resoruce group
# Functions
# Source:
Function Build-Signature ($customerId, $sharedKey, $date, $contentLength, $method, $contentType, $resource)
$xHeaders = "x-ms-date:" + $date
$stringToHash = $method + "`n" + $contentLength + "`n" + $contentType + "`n" + $xHeaders + "`n" + $resource
$bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
$keyBytes = [Convert]::FromBase64String($sharedKey)
$sha256 = New-Object System.Security.Cryptography.HMACSHA256
$sha256.Key = $keyBytes
$calculatedHash = $sha256.ComputeHash($bytesToHash)
$encodedHash = [Convert]::ToBase64String($calculatedHash)
$authorization = 'SharedKey {0}:{1}' -f $customerId,$encodedHash
return $authorization
# Source:
Function Post-OMSData($customerId, $sharedKey, $body, $logType)
$method = "POST"
$contentType = "application/json"
$resource = "/api/logs"
$rfc1123date = [DateTime]::UtcNow.ToString("r")
$contentLength = $body.Length
$signature = Build-Signature -customerId $customerId -sharedKey $sharedKey -date $rfc1123date -contentLength $contentLength -method $method -contentType $contentType -resource $resource
$uri = "https://" + $customerId + "" + $resource + "?api-version=2016-04-01"
$headers = @{
"Authorization" = $signature;
"Log-Type" = $logType;
"x-ms-date" = $rfc1123date;
"time-generated-field" = $TimeStampField;
$response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -Body $body -UseBasicParsing
return $response.StatusCode
# Main
$pools=Get-AzWvdHostPool -ResourceGroupName $ResourceGroup
Write-Host "Starting iteration at $now"
Write-Host "Get $($pools.Count) host pools"
$pools | ForEach {
Write-Host "`nWorking on pool $hostPoolName"
$sessionHosts=Get-AzWvdSessionHost -HostPoolName $_.Name -ResourceGroupName $rg
$sessionHosts | Add-Member -MemberType NoteProperty -Name "TimeStamp" -Value $now
Write-Host "Number of session hosts: $($sessionHosts.Count)"
# Send to log analytics
if ($sessionHosts.Count -gt 0) {
$response=Post-OMSData -customerId $WorkspaceId -sharedKey $WorkspaceKey -body ([System.Text.Encoding]::UTF8.GetBytes(($sessionHosts | ConvertTo-Csv|ConvertFrom-Csv|ConvertTo-Json -Depth 5))) -logType $LogTypeName
Write-Host "Data uploaded to $WorkspaceId. Response code: ",$response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment