Reference To install the module ::: https://support.scriptrunner.com/articles/#!trial/vmware

# Import PowerCLI module
Import-Module VMware.PowerCLI

# Connect to vCenter (replace with your credentials)
Connect-VIServer -Server vCenterServer -User user@domain.com -Password yourpassword

# Function to get VMs with high resource utilization
function Get-HighResourceVMs {
    $vms = Get-VM
    $highResourceVMs = @()

    foreach ($vm in $vms) {
        $stats = Get-Stat -Entity $vm -Stat "cpu.usage.average", "mem.usage.average" -Start (Get-Date).AddHours(-1) -Finish (Get-Date)
        $cpuUsage = $stats.Stat | Where-Object {$_.CounterId -eq "cpu.usage.average"} | Select-Object -ExpandProperty Average
        $memUsage = $stats.Stat | Where-Object {$_.CounterId -eq "mem.usage.average"} | Select-Object -ExpandProperty Average

        if ($cpuUsage -gt 80 -or $memUsage -gt 80) {
            $vm | Add-Member -NotePropertyName CPUUsage -NotePropertyValue $cpuUsage
            $vm | Add-Member -NotePropertyName MemoryUsage -NotePropertyValue $memUsage
            $highResourceVMs += $vm
        }
    }

    return $highResourceVMs
}

# Function to send report
function Send-Report {
    $highResourceVMs = Get-HighResourceVMs
    if ($highResourceVMs.Count -gt 0) {
        $report = "High Resource Utilization VMs:"
        foreach ($vm in $highResourceVMs) {
            $report += "`n- $vm.Name: CPU Usage = $($vm.CPUUsage)%, Memory Usage = $($vm.MemoryUsage)%"
        }

        # Replace with your preferred email sending method
        # For example, using Send-MailMessage:
        Send-MailMessage -To "your_email@example.com" -From "report@example.com" -Subject "High Resource Utilization Report" -Body $report
    }
}

# Send initial report
Send-Report

# Schedule the script to run every 4 hours
$action = New-JobAction -ScriptBlock {Send-Report}
Register-ScheduledJob -Name "HighResourceVMReport" -Trigger (New-JobTrigger -Daily -At 0,4,8,12,16,20) -Action $action

Podcast also available on PocketCasts, SoundCloud, Spotify, Google Podcasts, Apple Podcasts, and RSS.

Leave a comment

The Podcast

Join Naomi Ellis as she dives into the extraordinary lives that shaped history. Her warmth and insight turn complex biographies into relatable stories that inspire and educate.

About the podcast