Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell command to eject the device connected through usb does not work first time

Tags:

powershell

I have a java application which interacts with a device connected through USB drive. I want to eject the device after processing. The below command works, but I have to try in a loop to make sure its ejected.

powershell.exe ((New-Object -comObject Shell.Application).NameSpace(17).ParseName('E:\').InvokeVerb('Eject'))

Not sure if any issue with the command. Sometimes it works after 3 or 4 times.

Can anyone help?

Added the screen shot here: enter image description here

like image 240
Damu Avatar asked Nov 26 '25 05:11

Damu


1 Answers

I cannot reproduce the error, but it seems, that the type of the drive object changes from "USB Drive" to "Removable drive", when invoking the Eject verb.

You might want to add a short script to your routine. Something like:

$obj = (New-Object -comObject Shell.Application).namespace(17).ParseName('E:\')
$Type = $obj.Type
while ($Type-eq 'USB Drive'){
    $obj.InvokeVerb('Eject')
    $Type= $obj.Type
}

Then you don't have to run the code several times and wait for PowerShell to spin up.

Here it is as a one-liner:

powershell.exe -Command {$obj = (New-Object -comObject Shell.Application).namespace(17).ParseName('E:\');$Type = $obj.Type;while ($Type-eq 'USB Drive'){Write-Host 'Removing drive';$obj.InvokeVerb('Eject');$Type= $obj.Type}}

If you want to run the command in cmd and not in PowerShell, you need to format it like this:

powershell.exe -Command $obj = (New-Object -comObject Shell.Application).namespace(17).ParseName('E:\');$Type = $obj.Type;while ($Type-eq 'USB Drive'){Write-Host 'Removing drive';$obj.InvokeVerb('Eject');$Type= $obj.Type}
like image 91
Axel Andersen Avatar answered Nov 28 '25 06:11

Axel Andersen