Today’s oneliner is an incredibly fast way to check the usage of your VMware datastores. You should first connect to Virtual Center in the following way:
$VC = Connect-VIServer “YourVCServerName”
Here comes the oneliner:
Get-Datastore | Sort-Object Name | %{Get-View $_.Id} | Format-Table @{Label=”Name”;Expression={$_.info.name}}, @{Label=”NumVMs”;Expression={$_.vm.length}}
Only interested in datastores that are not used? Use the Where-Object cmdlet:
Get-Datastore | Sort-Object Name | %{Get-View $_.Id} | Where {$_.vm.length -eq 0} | Format-Table @{Label=”Name”;Expression={$_.info.name}}, @{Label=”NumVMs”;Expression={$_.vm.length}}
But watch out! Consider a vm with a disk in datastore A and the vmx in datastore B. When you create a snapshot of the vm, the delta files of all disks will be stored with the vmx (in datastore B). The script (as does the VI Client) will show the vm to be not connected to datastore A!
Enjoy!
Related posts:

[...] Powershell Oneliner #6 [...]
hi. nice one-liners, but the use of them causes this error if you try to implement them into functions :
code:
function listvmsperlun () {
connect-viserver $args[0]
Get-Datastore | Sort-Object Name | %{Get-View $_.Id} | Format-Table @{Label=”Name”;Expression={$_.info.name}}, @{Label=”NumVMs”;Expression={$_.vm.length}}
Disconnect-VIServer -Confirm:$false
}
result:
[PS1] O:\My Documents\WindowsPowerShellScripts> listvmsperlun vcenter
Name Port User
—- —- —-
server 443 NORWICH\user
out-lineoutput : Object of type “Microsoft.PowerShell.Commands.Internal.Format.FormatStartData” is not legal or not in the c
orrect sequence. This is likely caused by a user-specified “format-table” command which is conflicting with the default form
Hi, thanks.
That’s because Format-Table was used. Replace it with Select-Object and replace Label= with Name=.
Hugo
Thanks for the last comment, Hugo. Was looking a long time for that one!