$currentdate = (Get-Date).tostring("yyyy-MM-dd")
$transfilename = 'OldSnapsTranscript_' + $currentdate + '.txt'
$transfilepath = 'C:\scripts\Transcripts\' + $transfilename
Start-Transcript $transfilepath -NoClobber -Append
#Load PowerCLI snapins and dot source them
Add-PSSnapin vmware.vimautomation.core
. "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"
#Connect to vcenter
Connect-VIServer vcenterserver.company.com
#Generating timestamped log name for powercli html output
$outfilename = 'VMFreeSpace_' + $currentdate + '.htm'
$outfilepath = 'C:\Scripts\Output\' + $outfilename
$PoweredOnVMwithTools = Get-VM | Where-Object {($_.PowerState -eq "PoweredOn") -and (($_.Extensiondata.Guest.ToolsStatus -eq "toolsOk") -or ($_.Extensiondata.Guest.ToolsStatus -eq "toolsOld")) }
$DriveReportArray = @()
ForEach ($VM in $PoweredOnVMwithTools){
ForEach ($Drive in $VM.ExtensionData.Guest.Disk){
$Path = $Drive.DiskPath
#Calculations
$Freespace = [math]::Round($Drive.FreeSpace / 1MB)
$Capacity = [math]::Round($Drive.Capacity/ 1MB)
$SpaceOverview = "$Freespace" + "/" + "$capacity"
$PercentFree = [math]::Round(($FreeSpace)/ ($Capacity) * 100)
#VMs with less space
if ($PercentFree -lt 10) {
$newobj = New-Object -TypeName PSObject
$newobj | Add-Member -Type NoteProperty -Name VM -Value $VM.name
$newobj | Add-Member -Type NoteProperty -Name Disk -Value $Path
$newobj | Add-Member -Type NoteProperty -Name FreeMB -Value $Freespace
$newobj | Add-Member -Type NoteProperty -Name PercentFree -Value $PercentFree
$DriveReportArray += $newobj
}
} # End ForEach ($Drive in in $VM.Extensiondata.Guest.Disk)
} # End ForEach ($VM in $PoweredOnVMwithTools)
if ($DriveReportArray) { $DriveReportArray | Sort-Object FreeMB | ConvertTo-Html | Out-File $outfilepath }
#variables for email output
$eto = "youremail@company.com"
$efrom = "PowerCLI_Reports <PowerCLIReports@company.com>"
$esubject = "Virtual Machine Guest Disks Low Free Space Report"
If ($DriveReportArray) { $ebody = (Get-Content $outfilepath | Out-String) }
$eserver = "smtpserver.company.com"
If ($DriveReportArray) { Send-MailMessage -From $efrom -To $eto -Subject $esubject -BodyAsHtml -Body $ebody -smtpserver $eserver }
Else { Send-MailMessage -From $efrom -To $eto -Subject $esubject -Body "There are no VMs with low free space in this report" -smtpserver $eserver }