How to eject mounted ISO file on vCenter VMs and also answer the VM questions by Powershell

Sometimes on linux machines when you run the powershell script to unmount or eject the ISO file from the machine, a question will be appeared on the VM.

In this script, i tried to also answer that question and force the VM to unmount the ISO file from such kind of VMs.

There is one problem in this case, some times when you eject a ISO file then it takes between 5 to 10 second that vCenter will be notified about the appeared question, because of that I wrote “Start-Sleep -s 10” in the script to just wait for 10 second then execute the command to answer the question.

If you see that it does not work for you you can increase the number but it will take times to be completed.

Important note : the Linux machines that faced this issue, whenever the question appears on the VM, the VM will be pause for some seconds, so be careful about this because when it happens for some VMs that are part of a cluster then during appearing this question on the VM they cannot send or receive heartbeat to their cluster manager therefore some failover could happen for them.

cls
$vCenters = @('vcs.milad.local')
#In case that you need to run this script for several vCenter uncomment line below and write down you vcenter server instead of vcsServer01 ...
#$vCenters = @('vcsServer01','vcsServer02','vcsServer03')
$questionText="The guest operating system has locked the CD-ROM door and is probably using the CD-ROM*"
$username =  read-host "Please Enter your vCenter Admin account for example [email protected]"
$password = read-host  "Enter your password" 



Write-Host "vCenter credential accepted."
Write-Host "*************************************************************************"

foreach ($vcenter in $vCenters){

Connect-VIServer -server $vcenter -User $username -Password $password
$VMs = Get-VM 

if ($VMs) {
 foreach ($vm in $VMs){
  Write-Host "checking mounted iso file on $vm "
  $hasMountedISO = Get-VM $vm | Get-CDDrive | where {$_.IsoPath -ne $null} 
  if ($hasMountedISO -ne $null) {
  Write-Host "VM has a mounted ISO file"
  Get-VM $vm | Get-CDDrive| Set-CDDrive -NoMedia  -Confirm:$false 
  Start-Sleep -s 10
  $VMQ= Get-VM $vm| Get-VMQuestion |Select  -ExpandProperty text
    if($VMQ -like $questionText){
    Write-Host "The question has been answered"
    Get-VM $vm| Get-VMQuestion | Set-VMQuestion -Option button.yes -Confirm:$false
  }
  }
  }
  }
}










Leave a Reply

Your email address will not be published. Required fields are marked *

96 − = 89