Files
PowerShell/vCenter Tools/GetVMUpgradeInfo.ps1
T
2026-07-24 17:35:40 -07:00

292 lines
12 KiB
PowerShell

param (
[string]$vCenter = "",
[string]$cluster = "",
[string]$filename = "vmexport.xlsx",
[string]$Customer = "",
[switch]$Help = $false,
[switch]$SaveCred = $false
)
# Variables
$fileVersion = "1.0.0"
$fileDate = "2026-05-21"
$scriptName = Split-Path -Path $PSCommandPath -Leaf
# Display Script Banner
Write-Host "--------------------------------------------------" -ForegroundColor White
Write-Host "Collect VM Information for Upgrades" -ForegroundColor Green
Write-Host "Version $($FileVersion) ($($FileDate))" -ForegroundColor Green
Write-Host "Written by Charlie Silverman" -ForegroundColor Green
Write-Host "--------------------------------------------------" -ForegroundColor White
function CheckModuleInstalled($moduleName, $command) {
Write-Host "Checking that package $moduleName is installed..." -NoNewLine
if (-not(get-command $command -erroraction silentlycontinue)) {
Write-Host " Missing" -ForegroundColor Red
if (-not (Get-Module -ListAvailable -Name $moduleName)) {
$response = ""
while (($response -ne "yes") -and ($response -ne "no")) {
$response = (Read-Host "ImportExcel module not instaled. Install now? (yes/no)").ToLower()
}
if ($response -eq "no") {
Write-Host "Operation Cancelled." -ForegroundColor Yellow
exit
}
Write-Host "Installing PowerShell module $moduleName..." -NoNewLine
Install-Module -Name $moduleName -Scope CurrentUser -Force
Write-Host " Success" -ForegroundColor Green
}
Write-Host "Loading PowerShell module $moduleName..." -NoNewLine
Import-Module $moduleName
Write-Host " Success" -ForegroundColor Green
} else {
Write-Host " Found" -ForegroundColor Green
}
}
# Check for ImportExcel and install if missing
CheckModuleInstalled -moduleName "VCF.PowerCLI" -command "connect-viserver"
CheckModuleInstalled -moduleName "ImportExcel" -command "import-excel"
$moduleName = "ImportExcel"
Import-Module ImportExcel
if ($Help) {
Write-Host
Write-Host "Purpose: Generate a spreadsheet for VM Upgrades."
Write-Host "Command Syntax:"
Write-Host " $scriptName (-vcenter [vcenter host name]) (-cluster ""[cluster]"") (-filename ""[filename]"") (-customer ""[customer]""" -foregroundcolor green
Write-Host "Command Line Options:"
Write-Host
Write-Host -NoNewLine " -vCenter " -foregroundcolor Green
Write-Host "- The FQDN or IP address of a vCenter server."
Write-Host -NoNewLine " -cluster " -foregroundcolor Green
Write-Host "- The name of the cluster as shown in vCenter."
Write-Host -NoNewLine " -customer " -foregroundcolor Green
Write-Host "- The name of the customer to display on the sheet title."
Write-Host -NoNewLine " -filename " -foregroundcolor Green
Write-Host "- The CSV filename to save the result."
Write-Host
Write-Host "If any of the information is not provided, you will be prompted. If a credential has been previously stored, it will"
Write-Host "be used again unless the -savecred option is specified."
Write-Host
Write-Host "If a filename is not specified, the file vmexport.csv will be created in the current directory."
Write-Host
exit
}
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$quiet = Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
if ($vCenter -eq "") {
$vCenter = Read-Host "Enter name of vCenter Server"
}
if ($SaveCred) {
$credential = Get-Credential -Message "Enter credentials for vCenter server $vCenter"
$credential | Export-Clixml -path $env:USERPROFILE\kistools-$vcenter.cred
Write-Host "Saving credentials."
}
if (Test-Path -path $env:USERPROFILE\kistools-$vcenter.cred -PathType Leaf) {
$credentials = Import-Clixml -path $env:USERPROFILE\kistools-$vcenter.cred
Write-Host "Using stored credentials"
} else {
$credentials = Get-Credential -Message "Enter credentials for vCenter server $vCenter"
if (!$credentials) {
Write-Host "ERROR: No credentials were entered" -foregroundcolor yellow
}
}
if (Test-Path -path $filename -PathType Leaf) {
Write-Host "File $filename already exists." -ForegroundColor Yellow
exit
}
try {
Write-Host -NoNewLine "Connecting to vCenter $vcenter..."
$vcconn = Connect-VIServer $vcenter -Credential $credentials -ErrorAction SilentlyContinue
Write-Host " Success" -ForegroundColor green
} catch {
Write-Host " Failure" -ForegroundColor Yellow -BackgroundColor Red
exit
}
if ($cluster -eq "") {
$Clusterlist = Get-Cluster | Sort-Object
While (($cluster -eq "") -or (-not $cluster)) {
Write-Host "`nCluster Selection:`n"
for ($x = 0; $x -lt $Clusterlist.length; $x++) {
Write-Host "$(([string]($x+1)).PadLeft(3,' '))" -NoNewLine -ForegroundColor Green
Write-Host ": " -NoNewLine -ForegroundColor Gray
Write-Host "$($Clusterlist[$x].name)" -ForegroundColor Yellow
}
$Clusternum = Read-Host "`nSelect Cluster Number"
if ($Clusternum -as [int]) {
$Clusternum = [int]$Clusternum - 1
$cluster = $Clusterlist[$Clusternum]
}
}
$mycluster = get-cluster $cluster
} else {
$mycluster = get-cluster $cluster
}
# Collect base VMware Tools and Hardware version from first Host
$myhost = $mycluster | get-vmhost | select-object -first 1
$esxcli = Get-EsxCLI -VMHost $myhost -V2
$latestHW = ($myhost | Get-View).Capability.MaxSupportedVmVersion
$latestVMT = ($esxcli.software.vib.list.invoke() | Where-Object {$_.ID -match "VMware_locker_tools"}).Version
$latestHW
$latestVMT
exit
Write-Host "Gathering information about VMs in cluster $cluster..." -NoNewLine
$vmlist = $mycluster | get-vm
$vmcount = $vmlist.length
$vmresponse = @()
for ($x = 0; $x -lt $vmlist.length; $x++) {
$percent = [Math]::Round(($x / $vmlist.length) * 100,0)
Write-Progress -ID 1 -Activity "Collecting VM Information" -Status "Processing VM $($x+1) of $($vmlist.length)" -PercentComplete $percent
$thisvm = $vmlist[$x];
$thisvmguest = $thisvm | get-vmguest
$vmname = $thisvm.Name;
$vmhardwareversion = $thisvmguest.ExtensionData.HwVersion
$vmtoolsstatus = $thisvmguest.ExtensionData.ToolsRunningStatus
$vmtoolsversionstatus = $thisvmguest.ExtensionData.ToolsVersionStatus
$vmosname = $thisvmguest.OSFullName
$vmtoolsversion = $thisvmguest.ToolsVersion
$badvmnics = ($thisvm | get-NetworkAdapter | Where-Object {$_.Type -ne "Vmxnet3"}).length -gt 0
$thisvmobj = [PSCustomObject]@{
"Name" = $vmname
"VM Hardware Version" = $vmhardwareversion
"VMTools Status" = $vmtoolsstatus
"VMTools Version" = $vmtoolsversion
"VMTools Version Status" = $vmtoolsversionstatus
"Has Non vmxnet3 NICs" = $badvmnics
"VMHW Updated" = $null
"VMTools Updated" = $null
"In Prog" = ""
"Migrating" = ""
"Complete" = ""
}
$vmresponse += $thisvmobj
}
Write-Host "Disconnecting from vCenter $vcenter..." -NoNewLine
try {
$quiet = Disconnect-VIServer $vcenter -Confirm:$false
} catch {
Write-Host " FAILURE" -ForegroundColor Yellow - BackgroundColor Red
}
Write-Host " Success" -ForegroundColor Green
Write-Progress -ID 1 -Completed
Write-Host " Success" -ForegroundColor Green
Write-Host "Writing information about $($vmresponse.length) VMs to file $filename..." -NoNewLine
try {
$sheetTitle = "VM Export for Cluster $cluster - $timestamp"
if ($customer -ne "") {
$sheetTitle = "$customer - $sheetTitle"
}
$exceltable = $vmresponse | Export-Excel -path $filename -WorksheetName "vCenter VM Data" -PassThru -Autosize -FreezeTopRow `
-TableName "VMData" -TableStyle Medium15 -Title $sheetTitle -TitleBold -TitleSize 22 `
-TableTotalSettings @{ CPU = "Sum"; RAM = "Sum"; "Provisioned Storage" = "Sum"; "Used Space Original" = "Sum" }
} catch {
Write-Host
Write-Host "ERROR! Unable to create file $filename" -ForegroundColor Yellow
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red -BackgroundColor Yellow
}
try {
$sheet = $exceltable.Workbook.Worksheets["vCenter VM Data"]
$sheet.Column(3) | Set-ExcelRange -NFormat '#,##0 " GB"'
$sheet.Column(4) | Set-ExcelRange -NFormat '#,##0.00 " GB"'
$sheet.Column(5) | Set-ExcelRange -NFormat '#,##0.00 " GB"'
$sheet.Column(6) | Set-ExcelRange -NFormat '#,##0.00 " GB"'
Set-Format -Address $sheet.Cells["2:2"] -WrapText
$sheet.InsertColumn(1,1)
$sheet.Column(1).Width = 2
$sheet.Cells["I:R"].Style.HorizontalAlignment = "Center"
$sheet.Cells["C2:G2"].Style.HorizontalAlignment = "Center"
$sheet.Column(5).Width = 13
$sheet.Column(6).Width = 13
$sheet.Column(7).Width = 13
$sheet.Column(13).Width = 12
$sheet.Column(14).Width = 12
$sheet.Column(15).Width = 12
$sheet.Column(16).Width = 12
$sheet.Column(17).Width = 12
$sheet.Column(18).Width = 12
For ($counter = 3; $counter -lt 3 + $vmcount; ++$counter) {
$PFormula = '=IF(AND(COUNTIF(M' + $counter + ':O' + $counter + ',"X")<3,COUNTIF(M' + $counter + ':O' + $counter + ',"")<3),"X","")'
Set-ExcelRange -Address $sheet.Cells["P" + $counter] -Formula $PFormula
$QFormula = '=IF(OR(M' + $counter + '="O",N' + $counter + '="O",O' + $counter + '="O"),"X","")'
Set-ExcelRange -Address $sheet.Cells["Q" + $counter] -Formula $QFormula
$RFormula = '=IF(AND(M' + $counter + '="X",N' + $counter + '="X",O' + $counter + '="X"),"X","")'
Set-ExcelRange -Address $sheet.Cells["R" + $counter] -Formula $RFormula
$HFormula = '=if(AND($G' + $counter + '>0,$G' + $counter + '<>""), $F' + $counter + ',"")'
Set-ExcelRange -Address $sheet.Cells["H" + $counter] -Formula $HFormula
}
$datarange = "B3:R" + (2+$vmcount)
Add-ConditionalFormatting -Worksheet $sheet -Address $datarange -RuleType Expression -ConditionValue '=INDIRECT("VMData[@Disk Format]")="Thick"' -BackgroundColor Red -ForegroundColor White
Add-ConditionalFormatting -Worksheet $sheet -Address $datarange -RuleType Expression -ConditionValue '=INDIRECT("VMData[@Disk Format]")="O"' -BackgroundColor Orange
Add-ConditionalFormatting -Worksheet $sheet -Address $datarange -RuleType Expression -ConditionValue '=INDIRECT("VMData[@In Prog]")="X"' -BackgroundColor Yellow
Add-ConditionalFormatting -Worksheet $sheet -Address $datarange -RuleType Expression -ConditionValue '=INDIRECT("VMData[@Complete]")="X"' -BackgroundColor Green
$sheet.Cells["S4"].Value = "Total VMs:"
$sheet.Cells["S5"].Value = "Thick Provisioned:"
$sheet.Cells["S6"].Value = "Converting to Thin:"
$sheet.Cells["S7"].Value = "Partially Migrated:"
$sheet.Cells["S8"].Value = "In Progress:"
$sheet.Cells["S9"].Value = "Completed:"
$sheet.Cells["S10"].Value = "Remaining:"
$sheet.Cells["S12"].Value = "Original Space Usage:"
$sheet.Cells["S13"].Value = "New Space Usage:"
$sheet.Cells["S14"].Value = "Space Saved:"
$sheet.Cells["S15"].Value = "Savings:"
$sheet.Cells["S4:S15"].Style.HorizontalAlignment = "Right"
$sheet.Column(19).Width = 22
Set-ExcelRange -Address $sheet.Cells["T4"] -Formula '=COUNTA(VMData[Name])'
Set-ExcelRange -Address $sheet.Cells["T5"] -Formula '=COUNTIF(VMData[Disk Format], "<>Thin")'
Set-ExcelRange -Address $sheet.Cells["T6"] -Formula '=COUNTIF(VMData[Disk Format], "O")'
Set-ExcelRange -Address $sheet.Cells["T7"] -Formula '=COUNTIF(VMData[Migrating],"X")'
Set-ExcelRange -Address $sheet.Cells["T8"] -Formula '=COUNTIF(VMData[In Prog], "X")'
Set-ExcelRange -Address $sheet.Cells["T9"] -Formula '=COUNTIF(VMData[Complete], "X")'
Set-ExcelRange -Address $sheet.Cells["T10"] -Formula '=T4-T9'
$formula = '=SUM(H3:H' + (2+$vmcount) +')'
Set-ExcelRange -Address $sheet.Cells["T12"] -Formula $formula
Set-ExcelRange -Address $sheet.Cells["T12"] -NFormat '#,##0.00 " GB"'
Set-ExcelRange -Address $sheet.Cells["T13"] -Formula '=SUM(VMData[Used Space Now])'
Set-ExcelRange -Address $sheet.Cells["T13"] -NFormat '#,##0.00 " GB"'
Set-ExcelRange -Address $sheet.Cells["T14"] -Formula '=T12-T13'
Set-ExcelRange -Address $sheet.Cells["T14"] -NFormat '#,##0.00 " GB"'
Set-ExcelRange -Address $sheet.Cells["T15"] -Formula '=IF(T12>0,T14/T12,"")'
Set-ExcelRange -Address $sheet.Cells["T15"] -NFormat '#.00%'
$sheet.Column(8).Hidden = $true
$sheet.Column(20).Width = 14
} catch {
Write-Host
Write-Host "ERROR! Unable to create file $filename" -ForegroundColor Yellow
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red -BackgroundColor Yellow
try {
Close-ExcelPackage $exceltable
Remove-Item $filename
Remove-Item $filename
} catch {
Remove-Item $filename
Remove-Item $filename
}
}
$exceltable.Workbook.WorkSheets[1].Tables["VMData"].ShowFilter = $false
Close-ExcelPackage $exceltable
Disconnect-V
Write-Host " Success" -ForegroundColor Green