Istanbul/Turkey

PowerCLI - Datastore Capacity, Usage and Free Space Percentage Report

In this post, I am going to share a script that creates Datastore Capacity, Usage and Free Space Percentage Report and sends an email after the report is generated. You can use Windows task scheduler to recieve this report peridocally  as an email.

Import-Module VMware.VimAutomation.Core -ErrorAction SilentlyContinue
Connect-VIServer -Server YourVcenterIPAddress –user “admin@vsphere.local” –Pass "VcenterAdminPassword"
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('dd-MM-yyyy')
Function Percentcal {
    param(
    [parameter(Mandatory = $true)]
    [int]$InputNum1,
    [parameter(Mandatory = $true)]
    [int]$InputNum2)
    $InputNum1 / $InputNum2*100
}

$datastores = Get-Datastore | Sort Name
ForEach ($ds in $datastores)
{
    if (($ds.Name -match “Shared”) -or ($ds.Name -match “”))
    {
        $PercentFree = Percentcal $ds.FreeSpaceMB $ds.CapacityMB
        $PercentFree = “{0:N2}” -f $PercentFree
        $ds | Add-Member -type NoteProperty -name PercentFree -value $PercentFree
    }
}
$datastores | Select Name, Datacenter, @{N=”UsedSpaceGB”;E={[Math]::Round(($_.ExtensionData.Summary.Capacity – $_.ExtensionData.Summary.FreeSpace)/1GB,0)}},@{N=”TotalSpaceGB”;E={[Math]::Round(($_.ExtensionData.Summary.Capacity)/1GB,0)}} ,PercentFree |
Export-Csv C:\DataStoreCapacityReports\MonthlyDSReport_$CurrentDate.csv -NoTypeInformation
######Sending Email########
$fromaddress = “MonthlyDSUsedCapacity@yourdomain.com”
$toaddress = “emailaddress@yourdomain.com”
$Subject = “Monthly Data Store Usage Report”
$body = get-content “C:\DataStoreCapacityReports\emailbody.html”
$attachment = “C:\DataStoreCapacityReports\MonthlyDSReport_$CurrentDate.csv”
$smtpserver = “SMTPServerIPAddress”



$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)

 

You can customize the html file as you need.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    Some messages for the email recepients.
<hr>
  </body>
</html>

 

You can also create a task in Task Scheduler to automatically receive the report. Task Scheduler was not able to initiate PowerShell instance when I tried to run ps1 file directly on Task Scheduler. Therefor I had to create a batch file and run this batch file on Task Scheduler. I added this batch file just in case if you do have the problem I had.

cd "%~dp0"
start powershell -noexit -Command "cd 'C:\DataStoreCapacityReports'"
start powerShell -NoExit -Command ".\DSCapacityReportScript.ps1"

 

  • Hits: 547