Thursday, June 30, 2011

UpdateVMwareTools.ps1

######################################
# Prompt to specify vCenter & Cluster
######################################

$vCenterName = Read-Host "Which vCenter to connect to (FQDN)"
$clusterName = Read-Host "Which Cluster"

##############################
# Connect to specified vCenter
##############################

Connect-VIServer -server $vCenterName -Protocol https -User "UserName" -Password "Password"
##############################
# Get collection of VMs, create log file
##############################

$colVMs = get-cluster -name $clusterName | Get-VM
$logFile = New-Item -ItemType File -Path "C:\Powershell\temp\VMware-Tools-Update_$((get-date).toString('MM-dd-yyyy_hh.mmtt')).log"

##############################
# Get variables for each VM
##############################

foreach ($VM in $colVMs) {
    $VMPower = $VM.PowerState
    $VMName = $VM.name
    $OS = (Get-VMGuest $VM).OSFullName
    $vmID = get-vm $VM | foreach {get-view $_.Id}
    $vmToolsStatus = $vmID.Guest.ToolsStatus

##############################
# See if VM is powered on
##############################

    if ($VMPower -notmatch "PoweredON") {
        Write-Host $VMName `t "Powered OFF" -ForegroundColor Red
        Add-Content -Path $logFile -Value ($VMName + "`t`tNo Update`t`tPowered OFF")
        }

##############################
# See if VM has a Windows OS
##############################

        elseif ($OS -notlike "*Windows*"){
        Write-Host $VMName `t $OS -ForegroundColor Red
        Add-Content -Path $logFile -Value ($VMName + "`t`tNo Update`t`t" + $OS)
        }

##############################
# See if VM's tools need updating
##############################

            elseif ($vmToolsStatus -notmatch "toolsOld") {
            Write-Host $VMName `t $vmToolsStatus -ForegroundColor Red
            Add-Content -Path $logFile -Value ($VMName + "`t`tNo Update`t`t" + $vmToolsStatus)
            }
           
##############################
# Update tools on VMs that meet prerequisites
##############################

                else {
                Update-Tools $VM -NoReboot
                Write-Host $VMName `t $vmToolStatus `t "Upgrading Tools/No Reboot" -ForegroundColor Green
                Add-Content -Path $logFile -Value ($VMName + "`t`tInitialized`t`t" + $vmToolsStatus)
                }
    }

##############################
# Disconnect from vCenter
##############################

Disconnect-VIServer -server $global:DefaultVIServers -Force

##############################

No comments:

Post a Comment