This script will help update licenses on all your Azure VMs, output to csv and has the option to exclude specific virtual machine names. For my VMS I needed to make sure they are always using Windows_Client. You can run this with any automation software (Azure Automation, Github Actions, DevOps, FunctionApp) to make sure your VMs are licensed correctly.
$allSubscriptons = Get-AzSubscription
$vmDetails = foreach ($subscription in $allSubscriptons) {
$temp = Set-AzContext -Subscription $subscription.Name
$allResourceGroups = Get-AzResourceGroup
foreach ($rg in $allResourceGroups) {
$vms = Get-AzVM -ResourceGroupName $($rg.ResourceGroupName) | Select Name, LicenseType, ResourceGroupName, Tags
if ($vms) {
foreach ($vm in $vms) {
# Skip VMs with names 'AVDVM1' and 'AVDVM2'
if($vm.Name -eq 'AVDVM1' -or $vm.Name -eq 'AVDVM2') {
continue
}
[PSCustomObject]@{
vmName = $vm.Name
vmRG = $vm.ResourceGroupName
vmSub = $subscription.Name
vmLicense = $vm.LicenseType
}
}
}
}
}
$vmDetails | Export-Csv -Path "C:\Temp\VMLicenses.csv" -NoTypeInformation
$vmDetails | Write-Output
$selectedVMs = $vmDetails | Out-GridView -PassThru
$licenseSet = "Windows_Client"
forEach ($vm in $selectedVMs) {
$null = Set-AzContext -Subscription $vm.vmSub
$tempVM = Get-AzVm -ResourceGroupName $vm.vmRG -Name $vm.vmName
# Only update if LicenseType is null. Remove -Whatif when ready.
if ($null -eq $tempVM.LicenseType) {
Write-Host "Setting $($vm.vmName) to $licenseSet" -ForegroundColor Green
$tempVM.LicenseType = $licenseSet
Update-AzVM -ResourceGroupName $vm.vmRG -VM $tempVM -WhatIf
}
}
If you don't need a CSV and want to just update any VMs with missing license you can use or modify this script below.
#Updates virtual machine license on 1 subscription only.
$subscriptionName = "Subname"
$licenseSet = "Windows_Client"
# Set the context to the specified subscription
Set-AzContext -SubscriptionName $subscriptionName
$allResourceGroups = Get-AzResourceGroup
#Iterate over all resource groups in the current subscription
foreach ($rg in $allResourceGroups) {
$vms = Get-AzVM -ResourceGroupName $rg.ResourceGroupName
#Iterate over all VMs in the current resource group
foreach ($vm in $vms) {
# Skip VMs with names 'AVD002' and 'AVD001'
if($vm.Name -eq 'AVD002' -or $vm.Name -eq 'AVD001') {
continue
}
# Only work on VMs where LicenseType is null or not Windows_Client
if($null -eq $vm.LicenseType -or "Windows_Client" -ne $vm.LicenseType) {
Write-Host "VM $($vm.Name) in resource group $($rg.ResourceGroupName) has no LicenseType set or LicenseType is not Windows_Client" -ForegroundColor Yellow
# Uncomment the next two lines if you want to set the LicenseType and update the VM
# $vm.LicenseType = $licenseSet
# Update-AzVM -ResourceGroupName $rg.ResourceGroupName -VM $vm -NoWait
}
}
}