Enable TrustedLaunch, SecureBoot, and vTPM on Existing VMs

Script to enable Trusted Launch on existing Azure Gen2 virtual machines. The script will check if the VM is deallocated and enable Trusted launch, secure boot, and vtpm. After the change is completed, it prompts to start the virtual machine, but you can comment that out or add to the script to just start all virtual machines.

$results = @()

# Define the names of the target resource groups
$targetResourceGroups = @("RG1", "RG2")  # Modify the names accordingly

foreach ($rgName in $targetResourceGroups) {
    # Get VMs for the current resource group
    $vmsInRG = Get-AzVM -ResourceGroupName $rgName

    foreach ($vm in $vmsInRG) {
        $instanceView = Get-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Status
        if ($instanceView.HyperVGeneration) {
            $gen = $instanceView.HyperVGeneration
        } else {
            $gen = "V1"

        $obj = [PSCustomObject]@{
            VMname     = $vm.Name
            Generation = $gen

        $results += $obj

        # Check VM deallocated status
        $vmStatus = $instanceView.Statuses | Where-Object Code -Like 'PowerState/*'
        $isDeallocated = $vmStatus.Code -eq 'PowerState/deallocated'

        # If it's a Gen2 VM and is deallocated, then apply the Update-AzVM command to it
        if ($gen -eq "V2" -and $isDeallocated) {
            $vm | Update-AzVM -SecurityType TrustedLaunch -EnableSecureBoot $true -EnableVtpm $true
            # Prompt to start the VM after updating
            $startVM = Read-Host -Prompt "Do you want to start $($vm.Name)? (Y/N)"
            if ($startVM -eq 'Y') {
                Start-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name
                Write-Host "Starting $($vm.Name)..."

$results | Format-Table -AutoSize

More information can be found here: Enable Trusted launch on existing VMs – Azure Virtual Machines | Microsoft Learn

Share or Save this: