Hi!
I use the following script to remove vms from inventory from a currently connected host - after running script, all vms show up as ORPHANED in virtual center.
host is 3.5x - I think this happens on 4.x U1 as well
anyone know how to fix ?
Thanks in advance!!
script:
cls
c:
cd \
$ErrorActionPreference = "SilentlyContinue"
$allvms = Get-VM
$host = Get-VMHost
foreach ($vm in $allvms)
{
Write-Host "Removing VM" $vm "from Host Inventory" -ForegroundColor Yellow
#Remove-VM -VM $vm -Server $host -Confirm:$false
Remove-Inventory -Item $vm -Confirm:$false
}
The virtual machines become orphaned on the vCenter Server because you remove them while you are connected to a host.You better connect to the vCenter Server to remove the virtual machines. In that case the vCenter Server knows that they are removed. If you want to delete the virtual machines disks also, you have to add the -DeleteFromDisk parameter to the Remove-VM cmdlet. If you want to remove all the virtual machines on a host named MyESX you can do it like this:
Connect-VIServer vCenterServer Get-VMHost -Name MyESX | ` Get-VM | ` Remove-VM -DeleteFromDisk -Confirm:$false
Regards, Robert
Thanks for the response. However:
a) I should be able to remove from inventory while connected to a host - any changes should be communicated to vcenter in background just as all other scripts that I run do and work fine and changes are reflected in vcenter.
b) I simply want to remove from inventory, not delete the vm from disk.
Again, thanks for the response, but I would like a clean method for removing vms from a host without them showing up as orphaned.
Sorry, I misunderstood your question. If you remove a VM from an ESX host, this VM will show up in vCenter Server as orphaned. There is no way to prevent that. You can run your script connected to the ESX server to remove the virtual machine from the inventory of the ESX server. After that you can run the next script connected to the vCenter Server to remove all orphaned virtual machines from the vCenter Server:
Connect-VIServer vCenterServer Get-View -ViewType VirtualMachine | ` Where-Object { $_.Runtime.ConnectionState -like "orphaned" } | ` Get-VIObjectByVIView | ` Remove-Inventory -Confirm:$False
Remember that you can only remove virtual machines from the inventory that are powered off. This is the same if you connect to an ESX server or to the vCenter Server.
Thanks for the response - I used your code and the vms remained in virtualcenter with orphaned in italics.