A PowerShell script that logs detailed information about all connected USB devices, including their names, PNP device IDs, and descriptions, along with a timestamp. This tool is ideal for tracking USB connections over time for auditing or troubleshooting purposes.
Click to view script…
<#
.SYNOPSIS
Logs all USB devices connected to the system.
.DESCRIPTION
This script uses CIM/WMI to query for USB devices (by filtering for PNPDeviceIDs that start with "USB")
and logs their details (Name, PNPDeviceID, Description) along with a timestamp. The log is appended to a file,
which by default is stored in the same directory as the script (USBDeviceLog.txt).
.NOTES
Run this script with the necessary permissions.
Adjust the log file path if needed.
#>
# Define the log file location (you can change this to an absolute path if desired)
$logFilePath = Join-Path -Path $PSScriptRoot -ChildPath "USBDeviceLog.txt"
# Get the current timestamp
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Create the log entry header
$logEntry = "USB Device Log - $timestamp`r`n" + ("=" * 50) + "`r`n"
# Query for USB devices by filtering Win32_PnPEntity for entries with a PNPDeviceID starting with "USB"
try {
$usbDevices = Get-CimInstance -ClassName Win32_PnPEntity | Where-Object { $_.PNPDeviceID -like "USB*" }
}
catch {
Write-Error "Error querying USB devices: $_"
exit
}
if ($usbDevices) {
foreach ($device in $usbDevices) {
$logEntry += "Name : " + $device.Name + "`r`n"
$logEntry += "PNPDeviceID : " + $device.PNPDeviceID + "`r`n"
$logEntry += "Description : " + $device.Description + "`r`n"
$logEntry += ("-" * 40) + "`r`n"
}
}
else {
$logEntry += "No USB devices found." + "`r`n"
}
$logEntry += "`r`n"
# Append the log entry to the log file
try {
Add-Content -Path $logFilePath -Value $logEntry
Write-Host "USB devices logged successfully to $logFilePath" -ForegroundColor Green
}
catch {
Write-Error "Failed to write to log file: $_"
}