Have you ever wondered, how to eject CD on a remote computer with PowerShell. Well, I most certainly did. You may ask why? Well for pulling pranks of course. :) Yes, yes I know that I can just use Computer Management but where’s the fun in that right? Besides the PowerShell way would also enable us to schedule it. OK, so how to do it? I have to tell you, it is not as easy as it sounds, and there’s actually no pure PowerShell way to do it. As it turned out there’s not pure .NET method as well.
My first thought on how to do it was WMI (Windows Management Instrumentation), especially because of the remoting capability. Unfortunately, there is no method to eject CD in any of the standard namespaces. There is everything in WMI, except the things you need :). So, no love from WMI for this one.
Another idea that came to mind was using “Shell.Application” COM object. This particular object lows us to call context menu items on shell items. The following example iterates through shell items of type “CD Drive” in Namespace(17), which is your computer folder, and calls the “Eject” command with InvokeVerb() method.
$sh = New-Object -ComObject "Shell.Application" $sh.Namespace(17).Items() | Where-Object { $_.Type -eq "CD Drive" } | foreach { $_.InvokeVerb("Eject") }
So this one actually works like a charm. Now we have to figure out how to do it on a remote computer. Fortunately there is a thing called PowerShell remoting, which allows you to run PowerShell commands on a remote computer. You can do it like that:
Invoke-Command -ComputerName COMPUTERNAME -ScriptBlock { $sh = New-Object -ComObject "Shell.Application" $sh.Namespace(17).Items() | Where-Object { $_.Type -eq "CD Drive" } | foreach { $_.InvokeVerb("Eject") } }
There are a few things to consider here: Remote computer has to be configured for PowerShell remoting and you have to have administrative rights on target system in order for this to work.
There also a possibility to Eject CDs using “WMPlayer.OCX” control. The approach is very similar to above example, and it also works with PowerShell remoting:
$cds = (New-Object -ComObject "WMPlayer.OCX").cdromCollection for($i=0;$i -lt $cds.Count;$i++) { $cds.Item($i).Eject() }
That’s it for today. Have a lot of fun with ejecting CDs :)