Powershell/PowerCLI: using filter to disconnect all attached cdrom

VMware 0 Comments

Here is a simple and effective PowerShell/PowerCLI script to extract all virtual machines that have an iso attached to their cdrom and then disconnect them.

I have used a filter on the first part of the script to extract only Linux virtual machines to a text file.


$credential = Get-Credential
$v = "vcenter01"

Connect-VIServer -Server $v -Credential $credential
      Get-VM | where {$_.Guest.OSFullName -like "*Linux*" }| Get-CDDrive | Where {$_.IsoPath -ne $null} |`
      Select @{Expression={$_.Parent};Label="VM Name"},@{Expression={$_.IsoPath};Label="ISO Path"} | Export-Csv -Path "VM_With_CD.csv"

The second part of the script, read a text file (which contain 1 VM name by line ) and go through a loop for every vm and then disconnect the cdrom.


$credential = Get-Credential
$v = "vcenter01"

Connect-VIServer -Server $v -Credential $credential
      foreach ($vm in Get-Content .\list.txt) {
         try {
				Get-VM -name $vm -Server $v -ErrorAction Stop | Get-CDDrive -VM $vm -ErrorAction -SilentlyContinue | Set-CDDrive -Connected:$false -NoMedia -Confirm:$false
				Write "Disconnecting CD Drive from VM $vm in vCenter $v"  
	 
	         }
         catch [Exception]{
				Write "VM $vm Not Found in vCenter $v"
			  }
	
		}

Please note, on Linux machine if you disconnect a cdrom from a vm this way and this cdrom is still mounted, the machine will freeze/hang, so be sure to unmount any mounted cdrom from inside the guest before.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Leave a Reply

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