In past I have written on the same subject. That was based on “WMPlayer.OCX.7” object which seems to be failing in some of the cases. I stumbled on a COM object today which I can use reliably to eject CD/DVD drive without issues. There are some more approaches as well available in internet which use a C# code in PowerShell. They also will work as expected but this is in pure form of powershell.
IMAPI(Image Mastering API) Interface in Windows has several abilities in managing the CD/DVD/BD disk drives and the COM objects I used in my below script are from the same family.
The script is short and straightforward.
[CmdletBinding()] param( [switch]$Eject, [switch]$Close ) try { $Diskmaster = New-Object -ComObject IMAPI2.MsftDiscMaster2 $DiskRecorder = New-Object -ComObject IMAPI2.MsftDiscRecorder2 $DiskRecorder.InitializeDiscRecorder($DiskMaster) if ($Eject) { $DiskRecorder.EjectMedia() } elseif($Close) { $DiskRecorder.CloseTray() } } catch { Write-Error "Failed to operate the disk. Details : $_" }
I published this script on Technet Script library as well. You can download it from there
Comments on this entry are closed.
Great piece of Powershell code.
Under the elseif ($Close) , I think the Method should be $DiskRecoder.CloseTray() not $EjectMedia()
Thanks,
Frank :-0)
Thanks Frank. That’s a good catch. I corrected the code.
Thanks, this was handy when I accidentally ejected a tray and couldn’t close it.
Two things:
1) if there’s more than one CD/DVD tray you’ll need to select it by indexing $DiskMaster ($DiskMaster[0] for example),
also
2) to run the .InitializeDiscRecorder command I had to be in an elevated prompt.