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
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With