'How do I use a PowerShell script to eject all mass storage drives?

I've been using a USB hub to copy files to many flash drives. Afterwards, they need to be ejected. I don't want to eject them manually, one at a time.

How can I write a PowerShell script to eject all mass storage drives, without having to input the drive letters?



Solution 1:[1]

I searched all over and was not able to find a satisfactory answer that put it all together.

Here is the script that I came out with.

$volList = get-wmiobject -Class Win32_Volume | where{$_.drivetype -eq '2'}  
if ($volList){
    ForEach ($vol in $volList){
        $volLetter = $vol.DriveLetter
        echo "Ejecting drive $volLetter"
        $Eject =  New-Object -comObject Shell.Application
        $Eject.NameSpace(17).ParseName($volLetter).InvokeVerb("Eject")
    }
}
else {
    echo "No removable drive found"
}

This worked very well!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ytagger