miked
miked Working the technologies in local government.

VM Uptime Check


VM Uptime Check

I find one of the most annoying features of Hyper-V is that the uptime counter for a VM is essentially worthless. The counter does reset when a machine reboots, but it likewise resets when a VM live migrates to a new host. Here where I work we were plagued with a peculiar network issue that had the potential to disrupt CSV communications. We had to produce a report of machines that crashed to notify our customers. Provided there’s admin access, you can use the following script to scan through your VMM environment and get the uptime via WMI.

You do need to provide a error log path in the Get-Uptime function, a CSV path in the main body, and put your where conditions in the $computer variable declaration. Give it a whirl and happy scripting!

ipmo virtualmachinemanager




Function Get-Uptime { 
    [CmdletBinding()] 
    param ( 
        [Parameter(Mandatory=$false, 
                        Position=0, 
                        ValueFromPipeline=$true, 
                        ValueFromPipelineByPropertyName=$true)] 
        [Alias("Name")] 
        [string[]]$ComputerName=$env:COMPUTERNAME, 
        $Credential = [System.Management.Automation.PSCredential]::Empty 
        ) 
 
    begin{} 
	$errorPath = #Enter your error log path
    #Need to verify that the hostname is valid in DNS 
    process { 
        foreach ($Computer in $ComputerName) { 
            try { 
                $hostdns = [System.Net.DNS]::GetHostEntry($Computer) 
                $OS = Get-WmiObject win32_operatingsystem -ComputerName $Computer -ErrorAction Stop -Credential $Credential 
                $BootTime = $OS.ConvertToDateTime($OS.LastBootUpTime) 
                $Uptime = $OS.ConvertToDateTime($OS.LocalDateTime) - $boottime 
                $propHash = [ordered]@{ 
                    ComputerName = $Computer 
                    BootTime     = $BootTime 
                    Uptime       = $Uptime 
                    } 
                $objComputerUptime = New-Object PSOBject -Property $propHash 
                
                $objComputerUptime
               
                
                }  
            catch [Exception] { 
                "$computer $($_.Exception.Message)" |out-file -FilePath $errorPath -Append
                #return 
                } 
        } 
    } 
    end{} 
}


$cred = Get-Credential
$computers = $(get-scvirtualmachine |? #insert your where string here
$CSVPath = Read-Host ("Enter the path for the CSV file")
$uptimes = @()
$i = 1

foreach ($Computer in $computers)
{
    
    $uptimes += $(get-uptime -ComputerName $computer -Credential $cred)
    write-host $i
    $i++
}

$uptimes | export-csv -path $CSVPath

binary-1188505_1280

comments powered by Disqus