Sorry to open this back up, but for some reason the space calculations (Allocated, Free, Used) are showing a value of "0" for many of our VMs. However, these VMs show 40G allocated in the VC. Here is the code I am using:
Connect-VIServer <server>
-User
</server>
Get-Datastore | ForEach-Object {
$Datastore = $_
$Datastore | Get-VM | ForEach-Object {
$VM = $_
$AllocatedSpace = 0
$FreeSpace = 0
$VM.Guest.Disks | ForEach-Object {
$AllocatedSpace += $_.Capacity
$FreeSpace += $_.FreeSpace
}
$Report = "" | Select-Object "VM Name","Data Store","Data Store Folder","VM Allocated Space - MB","VM Used Space - MB","VM Free Space - MB","Power State",Owner,Project,Notes
$Report."VM name"= $VM.Name
$Report."Data Store"= $Datastore.name
$Report."Data Store Folder" = (Get-View -Id $Datastore.ParentFolderId).Name
$Report."VM Allocated Space - MB" = "" -f ($AllocatedSpace/1MB)
$Report."VM Used Space - MB" = "" -f (($AllocatedSpace - $FreeSpace)/1MB)
$Report."VM Free Space - MB" = "" -f ($FreeSpace/1MB)
$Report."Power State" = $VM.PowerState
$Report.Owner = (Get-Annotation -Entity $VM -CustomAttribute "Owner (email)").Value
$Report.Project = (Get-Annotation -Entity $VM -CustomAttribute "Project").Value
$Report.Notes = $VM.Description
$Report
}
} | Export-Csv -Path c:\temp\VMsWithDatastoresInfo-1021am.csv -NoTypeInformation
Doing some debugging, if I initially set the AllocatedSpace and FreeSpace vars to "" (nothing), I get the error below on some VMs:
-
Method invocation failed because http://System.String doesn't contain a method named 'op_Subtraction'.
At line:19 char:64
+ $Report."VM Used Space - MB" = "" -f (($AllocatedSpace - <<<< $FreeSpace)/1MB)
+ CategoryInfo : InvalidOperation: (op_Subtraction:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
-
This tells me I am querying the wrong value from the DB.
Any ideas?
BTW - how do I post "code" in the forum? I don't see any formatting styles in the message creation tool.