Sunday, April 13, 2014

Collect disk space detail and send it in email Powercli

This script will collect C Drive with less than 20% space on the VM and send email with nice HTML format.

I have improvised this script and can be found it under Versin 2 VM disk space detail send via email Powercli

  #####################################   
  ## http://kunaludapi.blogspot.com   
  ## Version: 1   
  ## Tested this script on   
  ## 1) Powershell v3   
  ## 2) Powercli v5.5   
  ## 3) Vsphere 5.x   
  #####################################  
 Add-PSSnapin vmware.vimautomation.core  
   
 # vCenter username password  
 $vCenterServer = "vCenterserver"  
 $vcenteruser = "domain\user"  
 $vcenterpasswd = "Password"  
   
 #connect vCenter Server  
 Connect-VIServer -Server $vCenterServer -User $vcenteruser -Password $vcenterpasswd  
   
 $FinalResult = @()  
 $Allvms = Get-View -ViewType “VirtualMachine” -filter @{”Guest.GuestState”=”running”; “Guest.GuestFullName”=”Windows"}  
 foreach ($vm in $Allvms) {  
   #Only C disk  
   $DriveC = $vm.Guest.Disk | Where-Object {$_.Diskpath -eq "C:\"}  
     
   #Calculations  
   $Freespace = [math]::Round($DriveC.FreeSpace / 1MB)  
   $Capacity = [math]::Round($DriveC.Capacity / 1MB)  
   $SpaceOverview = "$Freespace" + "/" + "$capacity"  
   $PercentFree = [math]::Round(($FreeSpace)/ ($Capacity) * 100)  
   
   #Report for all vms  
   $report = New-Object psobject  
   $report | Add-Member -MemberType NoteProperty -Name "VMName" -Value $VM.Name  
   $report | Add-Member -MemberType NoteProperty -Name "Free(MB)/Total(MB)" -Value $SpaceOverview  
   $report | Add-Member -MemberType NoteProperty -Name "%Free" -Value $PercentFree  
     
   #VMs with less space on C Drive  
   if ($report."%free" -lt 20) {  
     $finalResult += $report  
   }  
 }  
   
 #HTML format  
 $a = "<style>"  
 $a = $a + "BODY{background-color:peachpuff;}"  
 $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"  
 $a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle}"  
 $a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:PaleGoldenrod}"  
 $a = $a + "</style>"  
   
 #Send Email  
 $messageParameters = @{  
 Subject = "Alert! VMs with less than 20% on C drive"  
 Body = $finalResult | ConvertTo-HTML -head $a -Body "<H2>VMs with less than 20% on C drive</H2>"  
 From = "SpaceAlert@email.com"  
 To = "Employee@email.com"  
 SmtpServer = "smtp.exchange.com"  
 }
Send-MailMessage @MessageParameters  

Warning: All the testings are performed in lab environment.
Post a Comment