Comment

Would be cool if you could add " | where {$_.PowerState -eq "PoweredOn"} "

after $myVMs = Get-VM -Datastore $myDatastore -server $server

So we dont get errors on powered off vms.

Added!

By the way, is there any way to do the same with the datastores ?

Not sure I know what you mean here - you just want datastores with no running VMs to be excluded from the results? If so, yeah, that should be easy enough.