Search notes:

PowerShell: determine which application prevents an USB drive from being ejected

When trying to eject an external USB drive («Safely remove hardware and eject media»), Windows might respond with the message Problem Ejecting USB Mass Storage Device (This device is currently in use. Close any programs or windows that might be using the device, and then try again):
Unfortunately, the message does not reveal which program or application uses the USB drive. With PowerShell, it is possible to determine this application with the get-eventLog cmdLet:
get-eventLog -logName system                     |
  where-object  instanceId -eq 225               |
  select-object timeGenerated, message -first 1
Github repository about-PowerShell, path: /examples/Problem-Ejecting-USB-Mass-Storage-Device/readEventLog.ps1
This simple pipeline might print something like
TimeGenerated       Message
-------------       -------
2020-09-07 10:36:50 The application \Device\HarddiskVolume2\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MsMpEng.exe with process id 2684 stopped the removal or ejection for the device USB\VID_0480&PID_A200\20160603001495C.
If MsMpEng.exe is preventing the disk from being ejected, the disk might be taken offline with diskpart.exe

Same thing, but with the event viewer

BTW, this information can also be determined with the Event viewer (eventvwr.exe) by going to Windows Logs -> System -> Filter Current Log and the setting the Event ID to 225:

See also

openfiles.exe

Index