≡ Menu

Eject or Close CD/DVD Drive using PowerShell(alternative to windows media objects)

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.

  • frank June 11, 2014, 11:09 pm

    Great piece of Powershell code.

    Under the elseif ($Close) , I think the Method should be $DiskRecoder.CloseTray() not $EjectMedia()

    Thanks,
    Frank :-0)

    • Sitaram Pamarthi June 12, 2014, 9:07 pm

      Thanks Frank. That’s a good catch. I corrected the code.

  • Dabell March 3, 2022, 7:11 am

    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.