Functions/Get-DatastoreAnalysis.psm1

function Get-DatastoreAnalysis {

    param(
        [string]$Datastore,
        [string]$Cluster
    )

    $vms = ""
    if($Datastore -ne ""){
        $vms = Get-Datastore $Datastore | Get-VM
    } elseif($Cluster -ne ""){
        $vms = Get-Cluster $Cluster | Get-VM
    } else {
        return "Specify a parameter"
    }
    
    $report = @()

    foreach ($vm in $vms){
        write-host $vm.Name
        $view = Get-View $vm
        $hds = @()
        (Get-HardDisk $vm).ExtensionData | %{
            $hds += $_
        }
        $hds += "swap"
        foreach($hd in $hds){

            $row = '' | select Name, Provisioned, TotalUsed, Capacity, Partition, Datastore, VMDKSize, Thin
            $row.Name = $vm.Name
            $row.Provisioned = [math]::round($vm.ProvisionedSpaceGB , 2)
            $row.TotalUsed = [math]::round($vm.UsedSpaceGB , 2)
            if($hd -eq "swap"){
                $row.Capacity = ""
                $row.Partition = "swap"
                try{
                    $row.Datastore = ($vm.extensiondata.LayoutEx.file|?{$_.Type -eq "swap"}).name.split(" ")[0]
                }catch{
                    continue
                }
                $row.VMDKSize = [math]::round(($vm.extensiondata.LayoutEx.file|?{$_.Type -eq "swap"}).size / 1GB, 2)
                $row.Thin = ""
            }else{
                $row.Capacity = [math]::round(($hd | Measure-Object CapacityInKB -Sum).sum/1048576 , 2)
                $row.Partition = $hd.deviceinfo.label
                $row.Datastore = $hd.backing.filename.split(" ")[0]
                $row.VMDKSize = [math]::round(($vm.extensiondata.LayoutEx.file|?{$_.name -eq $hd.backing.filename.replace(".","-flat.")}).size / 1GB, 2)
                $row.Thin = $hd.Backing.ThinProvisioned
            }
            
            $report += $row
            
        }
    }

    return $report
    
}