Automating Hyper-V Virtual Machine Health Checks with PowerShell

Keeping Hyper-V virtual machines running smoothly is essential for a seamless IT environment. This PowerShell script automates the health checks of Hyper-V virtual machines, helping administrators monitor their status, resource allocation, and performance metrics easily. With this script, administrators can proactively address any issues that might impact VM performance or availability.
This script will:
1. Retrieve the status of all Hyper-V virtual machines.
2. Check CPU and memory usage for each VM.
3. Report on uptime and any error states.
By using this script, IT administrators can ensure their virtualized infrastructure remains healthy and responsive to business needs.

# Import the Hyper-V module
Import-Module Hyper-V
# Get all virtual machines
$vms = Get-VM
Write-Host "=== Hyper-V Virtual Machine Health Check ==="
foreach ($vm in $vms) {
    $status = $vm.State
    $uptime = (Get-Date) - $vm.Uptime
    $cpuUsage = (Get-VMProcessor -VM $vm).PercentageProcessorTime
    $memoryAssigned = "{0:N2} GB" -f ($vm.MemoryAssigned / 1GB)
    Write-Host "VM Name: $($vm.Name)"
    Write-Host "  Status: $status"
    Write-Host "  Uptime: $([math]::round($uptime.TotalHours, 2)) hours"
    Write-Host "  CPU Usage: $cpuUsage %"
    Write-Host "  Assigned Memory: $memoryAssigned"
    Write-Host "-------------------------------------"
}
Write-Host "Health check completed."