How to get the uptime/last reboot time for all Azure VMs

Sky High 311 Reputation points
2022-04-07T14:45:45.413+00:00

Hi Team,

How to get the uptime/last reboot time for all Azure VMs using PowerShell.
what kind of permissions needed for this activity on VM. Please suggest.

I did try with get-cim but it helped for few VM's. Our cloud environment has both Windows & Linux VMs.

Ciao

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
9,051 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. shiva patpi 13,366 Reputation points Microsoft Employee Moderator
    2022-04-15T06:10:42.313+00:00

    Hello @Sky High ,
    Can you take a look at the script mentioned in the below dicussion.

    https://stackoverflow.com/questions/42721460/azure-powershell-command-to-get-the-uptime-for-all-vms

    $AllVMs = Get-AzVM -Status | Where-Object { $_.PowerState -Like 'VM running' }
    $UptimeReport = @()

    //Walk through each VM
    foreach ($VM in $AllVMs) {

    # Get Subscription Information  
    $ctx = Get-AzContext  
    Write-Host "Check: '$($VM.Name)' in Subscription '$($ctx.Subscription.Name)'"  
      
    # Get the Activity Log of the VM  
    $VMAzLog = Get-AzLog -ResourceId $VM.Id `  
    | Where-Object { $_.OperationName.LocalizedValue -Like 'Start Virtual Machine' } `  
    | Sort-Object EventTimestamp -Descending `  
    | Select-Object -First 1  
    $BootTime = $VMAzLog.EventTimestamp  
    
    if ($BootTime) {  
        $Uptime = '{0}:{1:D2}:{2:D2}' -f (24 * $TimeSpan.Days + $TimeSpan.Hours), $TimeSpan.Minutes, $TimeSpan.Seconds  
    }  
    else {  
        $Uptime = "n/a"   
    }  
    
    if ($BootTime) {  
          
        $TimeSpan = New-TimeSpan -Start $($VMAzLog.EventTimestamp) -End (Get-Date)  
    
        $UptimeReport += [PSCustomObject]@{  
            VM             = $VM.Name  
            SubscriptionId = $ctx.Subscription.id  
            Uptime         = $Uptime  
        }  
    }  
    

    }

    regards,
    Shiva


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.