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

1.8k views Asked by At

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?

1

There are 1 answers

0
Ytagger On

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!