Hey folks! I'm trying to control the optical drive tray using PowerShell since it doesn't natively support this. I came up with a simple C# script for ejecting and closing the tray. It works perfectly on my end, but I'm relatively new to C#. Can anyone with experience in C# take a look and confirm if it's solid? Here's the code:
```
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public class OpticalDrive
{
[DllImport("winmm.dll")]
static extern int mciSendString(string command, string buffer, int bufferSize, IntPtr hwndCallback);
public static void Eject(string driveLetter)
{
mciSendString($"open {driveLetter}: type CDAudio alias drive", null, 0, IntPtr.Zero);
mciSendString("set drive door open", null, 0, IntPtr.Zero);
mciSendString("close drive", null, 0, IntPtr.Zero);
}
public static void Close(string driveLetter)
{
mciSendString($"open {driveLetter}: type CDAudio alias drive", null, 0, IntPtr.Zero);
mciSendString("set drive door closed", null, 0, IntPtr.Zero);
mciSendString("close drive", null, 0, IntPtr.Zero);
}
}
'@
[OpticalDrive]::Eject('E')
[OpticalDrive]::Close('E')
```
3 Answers
Your script looks mostly good! I think it's relying on the winmm.dll to handle the commands, which is a common approach for this in C#. Just make sure you're aware that it works with the Windows multimedia commands. Could be super fun to use for a prank, too!
Solid approach! You might also consider handling exceptions to catch any errors that come up while executing the commands. It's always good to have a fallback plan. That way, if something goes wrong, you can easily troubleshoot the issue!
Just a heads up—while this isn't strictly a PowerShell issue, your implementation is simple and seems effective. You're using correct calls to send commands for the eject and close functions. If you want more advanced control, looking into the IMAPI2 methods might help!
To follow up, the method you found seems nice! Just remember, for ejecting and closing, it's often the same command to either action, unless you're dealing with more complex devices.
For sure! There was this old program called cokeholder.exe that would pop the tray out—it was hilarious! Sadly, antivirus software flagged it as a nuisance, so it’s disappeared.