How to Use PowerShell to Safely Eject a USB Drive

The Dangers of Yanking the Drive

Pulling a USB flash drive or an external hard drive out of a Windows computer without safely ejecting it first is a recipe for data corruption. Windows heavily utilizes “write caching,” meaning it will tell you a file transfer is complete, but it is actually holding the final chunks of data in RAM, waiting for an idle moment to write them to the physical USB drive. If you pull the drive before this background process finishes, the filesystem will be corrupted.

While you can easily click the “Safely Remove Hardware” icon in the Windows taskbar, system administrators writing automated backup scripts need a way to trigger this safe ejection process programmatically. If your PowerShell script finishes copying database backups to an external drive, it should securely eject that drive so it can be physically unplugged by a junior technician.

Using the Shell.Application COM Object

Surprisingly, PowerShell does not have a native, built-in Eject-Disk cmdlet. To accomplish this, we must interact directly with the Windows Shell (the underlying GUI engine of the operating system) by instantiating a COM object.

In this example, we assume your external USB drive is mounted as the E:\ drive.

$DriveLetter = "E:"
$Shell = New-Object -ComObject Shell.Application

Executing the Eject Command

Once you have access to the Shell object, you must target the specific drive letter using the Namespace method, and then invoke the specific context menu verb used for ejection.

In the Windows API, the specific command to eject a volume is InvokeVerb("Eject").

$Shell.Namespace(17).ParseName($DriveLetter).InvokeVerb("Eject")

Note: The magic number 17 in the Namespace method tells the Windows Shell to specifically target “My Computer” (This PC), which is required to interact with physical drive letters.

Handling Open File Locks

When you run the script, Windows will execute the exact same procedure as if you clicked the button in the taskbar. It will flush the write cache and detach the filesystem.

If another application (or even your own PowerShell script) currently has a file open on the USB drive, the command will fail, and Windows will display a standard warning pop-up stating, “This device is currently in use. Close any programs or windows that might be using the device, and then try again.”

To prevent this, ensure your PowerShell script explicitly closes all file handles and changes its working directory (using Set-Location C:\) away from the USB drive before attempting to invoke the eject verb.

# Good Scripting Practice:
Set-Location C:\
Start-Sleep -Seconds 2 # Give the OS a moment to release handles
$Shell.Namespace(17).ParseName("E:").InvokeVerb("Eject")

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.