Hi,
Is there a faster way to get the datacenter name using Get-View and the viewtype VirtualMachine.
I found the following way:
Get-View -ViewType VirtualMachine -filter @{ "name" = "mtl1fsit02" } | Select-Object -Property Name,
@{ Label = "GuestOSName"; Expression = { $_.summary.guest.guestfullname } },
@{ Label = "Datacenter"; Expression = { (Get-view (Get-View (Get-view $_.parent).parent).Parent).name } }
Thanks guys
I think that calculated property to get the datacenter will not work in all situations.
It assumes your VMs are 3 levels down from the datacenter, which is not always the case.
I personally would use a loop, going up through the parents, until it find a datacenter object.
something like this
@{N="Datacenter";E={
$parentObj = Get-View $_.Parent
while($parentObj -isnot [VMware.Vim.Datacenter]({
$parentObj = Get-View $parentObj.Parent
}
$parentObj.Name
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
I think that calculated property to get the datacenter will not work in all situations.
It assumes your VMs are 3 levels down from the datacenter, which is not always the case.
I personally would use a loop, going up through the parents, until it find a datacenter object.
something like this
@{N="Datacenter";E={
$parentObj = Get-View $_.Parent
while($parentObj -isnot [VMware.Vim.Datacenter]({
$parentObj = Get-View $parentObj.Parent
}
$parentObj.Name
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Thanks LucD! 🙂
Just to confirm that the script work with the LucD tip.
This will list all the VM with the properties: Name, OS Full Name and the Datacenter Name.
Get-View -ViewType VirtualMachine |
Select-Object -Property Name,
@{ Label = "OSName"; Expression = { $_.summary.guest.guestfullname } },
@{ Label = "DataCenter"; Expression = {
$parentObj = Get-View $_.Parent
while ($parentObj -isnot [VMware.Vim.Datacenter])
{$parentObj = Get-View $parentObj.Parent}
$parentObj.Name} }
You can also try it like below.
foreach($dc in Get-View -ViewType Datacenter -Property Name,VmFolder){
foreach($vm in Get-View -ViewType VirtualMachine -Filter @{"Summary.Config.Template"="False"} -SearchRoot $dc.VmFolder -Property Name){
$vm.Name;
$dc.Name;
}
}
Probably you will anyway need to pass through datacenter so why not to use loop with it?
Small typo you had LucD for the closing ')' ...
below is corrected one
@{N="Datacenter";E={
$parentObj = Get-View $_.Parent
while($parentObj -isnot [VMware.Vim.Datacenter]){
$parentObj = Get-View $parentObj.Parent
}
$parentObj.Name
}