Saturday, May 5, 2018

Eject usb drive but not all of them

Eject usb drive but not all of them

Using the windows 10 icon, "eject the media", is slow because windows start all my sleeping usb drives before i can click "eject safely"

I wanted to eject some drive without waiting for the windows to open
I did not want to eject my sleeping usb drives that i use for storage

So, I designed this little powershell script to do so

##### powershell script #####

### requirements
# because this script is not signed
# (this will allow unsigned local powershell scripts to run)
#   windows 7
#     Set-ExecutionPolicy RemoteSigned #################################
#   windows 10
#     Set-ExecutionPolicy -scope CurrentUser RemoteSigned ##############
#   run it in powershell ISE interface runned as admin


$donotejectserials = @(`
"FAFFFFF0FDF2F7F1BFC15635",`
"2GEWLRPL",`
"14510E6CDA88")

# get serial i do not want to eject - list all usb drives
#get-Disk | Where {($_.BusType -eq "USB")}

$allusbdisk = get-Disk | Where {($_.BusType -eq "USB")}

foreach ($usbdisk in $allusbdisk)
    {
    $founddonoteject = 0
    foreach ($donotejectserial in $donotejectserials)
        {
        if ($usbdisk.serialnumber -like "*$donotejectserial*")
            {
            $founddonoteject = 1
            }
        #write-host "Serials: " $usbdisk.serialnumber " ----- " $donotejectserial " ----- " $founddonoteject
        }
    if ($founddonoteject -eq 0)
        {
       
        $letter = ($usbdisk | Get-Partition ).DriveLetter
        write-host "Ejecting: " $letter " ----- " $usbdisk.friendlyname " ----- " $usbdisk.serialnumber
        (New-Object -comObject Shell.Application).NameSpace(17).ParseName("$($letter):").InvokeVerb('Eject')
        }
    else
        {
        #write-host "NOT Ejecting: " $usbdisk.friendlyname
        }
    }