To create a PowerShell script that validates all VMs with high CPU usage and logs the host where they are running, you can use the VMware PowerCLI module to interact with vCenter Server and retrieve VM performance data. Additionally, you can set up a scheduled task to run the script hourly. Below is a sample PowerShell script:
# Load VMware PowerCLI module
Import-Module VMware.PowerCLI
# Set vCenter Server connection details
$vcServer = "vcenter.example.com"
$vcUsername = "administrator@vsphere.local"
$vcPassword = "your_vcenter_password"
# Connect to vCenter Server
Connect-VIServer -Server $vcServer -User $vcUsername -Password $vcPassword
# Function to check VM CPU usage and log the host
function CheckHighCPUMetrics {
# Get all VMs
$vms = Get-VM
foreach ($vm in $vms) {
# Get VM CPU usage metrics for the last hour
$cpuMetrics = Get-Stat -Entity $vm -Stat "cpu.usage.average" -Realtime -MaxSamples 12 | Measure-Object -Property Value -Average
# Define the threshold for high CPU usage (adjust as needed)
$cpuThreshold = 90
# Check if CPU usage exceeds the threshold
if ($cpuMetrics.Average -gt $cpuThreshold) {
# Get the host where the VM is running
$vmHost = Get-VMHost -VM $vm
# Log the VM and host details
Write-Host "High CPU Usage Detected for VM $($vm.Name) (Average CPU Usage: $($cpuMetrics.Average)%) on Host $($vmHost.Name)" -ForegroundColor Red
Add-Content -Path "C:\Logs\HighCPU_VM_Logs.txt" -Value "$(Get-Date) - High CPU Usage Detected for VM $($vm.Name) (Average CPU Usage: $($cpuMetrics.Average)%) on Host $($vmHost.Name)"
}
}
}
# Execute the function to check high CPU usage
CheckHighCPUMetrics
# Disconnect from vCenter Server
Disconnect-VIServer -Server $vcServer -Confirm:$false
In this script:
- The script connects to vCenter Server using the provided credentials.
- The
CheckHighCPUMetricsfunction retrieves the VMs and their CPU usage metrics for the last hour using theGet-Statcmdlet. - If a VM’s CPU usage exceeds the defined threshold (90% in this example), the script logs the VM and host details to the specified log file.
- The script disconnects from vCenter Server after executing the function.
To schedule the script to run every hour, you can create a scheduled task using the Windows Task Scheduler:
- Save the PowerShell script with a .ps1 extension (e.g.,
CheckHighCPU.ps1). - Open the Windows Task Scheduler.
- Click “Create Basic Task” and follow the wizard to set up a new task.
- In the “Action” section, select “Start a program” and browse to the PowerShell executable (e.g.,
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe). - In the “Add arguments” field, provide the full path to your PowerShell script (e.g.,
C:\Scripts\CheckHighCPU.ps1). - Set the task schedule to run hourly.
- Finish the wizard to create the scheduled task.
Now, the script will run every hour, checking for VMs with high CPU usage and logging the information to the specified log file. Adjust the CPU threshold or log path as needed based on your requirements.