[Request] Simplified USB Drive Connection/Disconnection Logging Feature

Post Reply
danalec
Posts: 2
Joined: Jul 30th, 2025, 1:14 pm

[Request] Simplified USB Drive Connection/Disconnection Logging Feature

Post by danalec »

I’m looking for a feature in USB Safely Remove to log the connection and disconnection of removable drives with timestamps.
This would be a simplified version of verbose logging, capturing only the essentials: the drive letter, event type (connected/disconnected), and the exact time of the event. For example, a log entry might look like:

Code: Select all

2025-07-30 10:25:15 | Connected | Drive: E:
2025-07-30 10:30:22 | Disconnected | Drive: E:
The goal is to track when USB drives are plugged in or removed without the detailed output of full verbose logging, making it easier to review. Ideally, the logs would be saved to a file (e.g., C:\Logs\USBEvents.log) and include only these key details for simplicity.

My current code is like this but I'd like to see this kind of lightweight logging in USB Safely Remove.
Could it be considered for a future update?

Code: Select all

# Define log file path
$logFile = "C:\Logs\USB_Log.txt"

# Ensure log directory exists
$logDir = Split-Path $logFile -Parent
if (-not (Test-Path $logDir)) {
    New-Item -ItemType Directory -Path $logDir | Out-Null
}

# Function to write to log file
function Write-Log {
    param($Message)
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$timestamp - $Message" | Out-File -FilePath $logFile -Append
}

# Register WMI event for USB drive connection/disconnection
$query = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 2"
Register-WmiEvent -Query $query -SourceIdentifier "USBConnect" -Action {
    $drive = $Event.SourceEventArgs.NewEvent.TargetInstance
    Write-Log "USB Drive Connected: $($drive.DeviceID) ($($drive.VolumeName))"
}

$query = "SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 2"
Register-WmiEvent -Query $query -SourceIdentifier "USBDisconnect" -Action {
    $drive = $Event.SourceEventArgs.NewEvent.TargetInstance
    Write-Log "USB Drive Disconnected: $($drive.DeviceID) ($($drive.VolumeName))"
}

# Keep script running to monitor events
Write-Host "Monitoring USB drive events. Press Ctrl+C to stop."
while ($true) { Start-Sleep -Seconds 3600 }
Thanks,
User avatar
Igor
Developer
Posts: 609
Joined: Nov 1st, 2007, 12:44 pm
Location: Saint Petersburg
Contact:

Re: [Request] Simplified USB Drive Connection/Disconnection Logging Feature

Post by Igor »

Hi Danalec,
Thank you for your detailed feature request. Yes, that's a great idea and it will be considered for one of the nearest versions.
Post Reply