PowerCLI Scripts for VMware Daily Administration and Reporting

Prerequisites

Before running these scripts, ensure you have the VMware PowerCLI module installed and are connected to your vCenter Server. You can connect by running the following command in your PowerShell terminal: Connect-VIServer -Server Your-vCenter-Server-Address

Script 1: General VM Inventory Report

This script gathers essential information about all virtual machines in your environment and exports it to a CSV file for easy analysis.

# Description: Exports a detailed report of all VMs to a CSV file.# Usage: Run the script after connecting to vCenter.Get-VM | Select-Object Name, PowerState, NumCpu, MemoryGB, UsedSpaceGB, ProvisionedSpaceGB, @{N='Datastore';E={[string]::Join(',', (Get-Datastore -Id $_.DatastoreIdList))}}, @{N='ESXiHost';E={$_.VMHost.Name}}, @{N='ToolsStatus';E={$_.ExtensionData.Guest.ToolsStatus}} | Export-Csv -Path .\VM_Inventory_Report.csv -NoTypeInformationWrite-Host 'VM Inventory Report has been generated: VM_Inventory_Report.csv'

Plain TextCopy

Script 2: VM Performance Report (CPU & Memory)

This script checks the average CPU and memory usage for all powered-on VMs over the last 24 hours and exports any that exceed a defined threshold (e.g., 80%).

# Description: Identifies VMs with high CPU or Memory usage over the last day.# Usage: Adjust the $threshold variable as needed.$threshold = 80 # CPU/Memory Usage Percentage Threshold$vms = Get-VM | Where-Object { $_.PowerState -eq 'PoweredOn' }$report = @()foreach ($vm in $vms) {    $stats = Get-Stat -Entity $vm -Stat cpu.usagemhz.average, mem.usage.average -Start (Get-Date).AddDays(-1) -IntervalMins 5    $avgCpu = ($stats | where MetricId -eq 'cpu.usagemhz.average' | Measure-Object -Property Value -Average).Average    $avgMem = ($stats | where MetricId -eq 'mem.usage.average' | Measure-Object -Property Value -Average).Average    if ($avgCpu -and $avgMem) {        $cpuUsagePercent = [math]::Round(($avgCpu / ($vm.NumCpu * $vm.VMHost.CpuTotalMhz)) * 100, 2)        $memUsagePercent = [math]::Round(($avgMem / ($vm.MemoryMB * 1024)) * 100, 2)        if ($cpuUsagePercent -gt $threshold -or $memUsagePercent -gt $threshold) {            $report += New-Object PSObject -Property @{                VMName = $vm.Name                AvgCPUUsagePct = $cpuUsagePercent                AvgMemoryUsagePct = $memUsagePercent            }        }    }}$report | Export-Csv -Path .\VM_High_Performance_Report.csv -NoTypeInformationWrite-Host 'High Performance Report has been generated: VM_High_Performance_Report.csv'

Plain TextCopy

Script 3: ESXi Host Compute Resources Left

This script reports on the available CPU and Memory resources for each ESXi host in your cluster, helping you plan for capacity.

# Description: Reports the remaining compute resources on each ESXi host.# Usage: Run the script to get a quick overview of host capacity.Get-VMHost | Select-Object Name,     @{N='CpuUsageMHz';E={$_.CpuUsageMhz}},     @{N='CpuTotalMHz';E={$_.CpuTotalMhz}},     @{N='CpuAvailableMHz';E={$_.CpuTotalMhz - $_.CpuUsageMhz}},    @{N='MemoryUsageGB';E={[math]::Round($_.MemoryUsageGB, 2)}},     @{N='MemoryTotalGB';E={[math]::Round($_.MemoryTotalGB, 2)}},    @{N='MemoryAvailableGB';E={[math]::Round($_.MemoryTotalGB - $_.MemoryUsageGB, 2)}} | Format-Table

Plain TextCopy

Script 4: Report on Powered-Off VMs

This simple script quickly lists all virtual machines that are currently in a powered-off state.

# Description: Lists all VMs that are currently powered off.# Usage: Run the script to find unused or decommissioned VMs.Get-VM | Where-Object { $_.PowerState -eq 'PoweredOff' } | Select-Object Name, VMHost, @{N='LastModified';E={$_.ExtensionData.Config.Modified}} | Export-Csv -Path .\Powered_Off_VMs.csv -NoTypeInformationWrite-Host 'Powered Off VMs report has been generated: Powered_Off_VMs.csv'

Plain TextCopy

Script 5: Audit Who Powered Off a VM

This script searches the vCenter event logs from the last 7 days to find who initiated a ‘power off’ task on a specific VM.

# Description: Finds the user who powered off a specific VM within the last week.# Usage: Replace 'Your-VM-Name' with the actual name of the target VM.$vmName = 'Your-VM-Name'$vm = Get-VM -Name $vmNameGet-VIEvent -Entity $vm -MaxSamples ([int]::MaxValue) -Start (Get-Date).AddDays(-7) | Where-Object { $_.GetType().Name -eq 'VmPoweredOffEvent' } | Select-Object CreatedTime, UserName, FullFormattedMessage | Format-List

Plain TextCopy

Script 6: Check for ESXi Host Crashes or Disconnections

This script checks for ESXi host disconnection events or host error events in the vCenter logs over the past 30 days, which can indicate a crash or network issue (Purple Screen of Death – PSOD).

# Description: Searches for host disconnection or error events in the last 30 days.# Usage: Run this to investigate potential host stability issues.Get-VIEvent -MaxSamples ([int]::MaxValue) -Start (Get-Date).AddDays(-30) | Where-Object { $_.GetType().Name -in ('HostCnxFailedEvent', 'HostDisconnectedEvent', 'HostEsxGenericPanicEvent', 'EnteredMaintenanceModeEvent') } | Select-Object CreatedTime, HostName, FullFormattedMessage | Sort-Object CreatedTime -Descending | Export-Csv -Path .\Host_Crash_Events.csv -NoTypeInformationWrite-Host 'Host crash/disconnection event report has been generated: Host_Crash_Events.csv'

Plain TextCopy

Leave a comment