kerpekri
kerpekri

Reputation: 377

Azure powershell command to get the uptime for all vms

I am trying to generate a report where can I see uptime for all my VMs using PowerShell.

We are using AzureRmVM-(Resource manager) for those VMs.

At the moment I have found something like this:

ForEach ($vm in $vmsList) { $vm.Name + " - " + $vm.ResourceGroupName }

get-vm | where {$_.state -eq 'running'} | sort Uptime | select Name,Uptime,@{N="MemoryMB";E={$_.MemoryAssigned/1MB}},Status

How can I do that using powershell - rm(Resource manager)?

Upvotes: 2

Views: 8000

Answers (1)

Gill-Bates
Gill-Bates

Reputation: 679

Collect all running VMs of your Subscription:

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

Then interate through each VM, catch the Audit Log, search for the VM start and calculate the Time difference to the current Time.

# Create Custom Object
$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
        }
    }
}

Finally, print the Result:

# Print Result
return $UptimeReport | Sort-Object -Property VM | ft * -AutoSize

Upvotes: 3

Related Questions