Dismount removable storage

I want the ability to remove any mounted ISO or USB from Windows 10 or 11 (physical or Hyperv VM)
I’m testing this from a Dell Optiplex running Windows 11 Pro. I’m getting the error “You cannot call a method on a null-valued expression.”

Here is code I’ve been working from: (can’t remember where i found it so thanks to whoever posted this code)

foreach ($disk in $removableDisks) {
$driveLetter = (Get-Partition -DiskNumber $disk.Number | Get-Volume).DriveLetter
if ($driveLetter) {
$driveEject = New-Object -comObject Shell.Application
$driveEject.Namespace(17).ParseName(“$DriveLetter”).InvokeVerb(“Eject”)
}
}

Hi,

Firstly, when posting code in the forum, please can you use the preformatted text </> button. It really helps us with readability, and copying and pasting your code (we don’t have to faff about replacing curly quote marks to get things working). If you can’t see the </> in your toolbar, you will find it under the gear icon.

From a quick test, the ParseName() method expects the drive letter to be passed with a colon, e.g. I:, but Get-Volume returns the letter sans colon:

PS E:\Temp> (Get-Partition -DiskNumber 1 | Get-Volume).Driveletter
D

Try:

$driveEject.NameSpace(17).ParseName("${DriveLetter}:").InvokeVerb("Eject")

There is no error produced from this code due to $removableDisks being empty. I think you’re missing some code. When you fix the formatting of the code, please add all the required code to test/help you.

Thanks @matt-bloomfield and @krzydoug . There was definitely something missing. Here is what I got working. It ejects CDs, ISOs and USB sticks.

$vol= (Get-WmiObject -Class Win32_Volume | where {$_.drivetype -eq '2' -or $_.drivetype -eq '5'}  )

foreach ($disks in $vol)  {
    $Eject =  New-Object -comObject Shell.Application
    $Eject.NameSpace(17).ParseName($disks.driveletter).InvokeVerb("Eject")
}

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.