#requires -Version 5.1 <# Infostruction USB file-change monitor, revision 2026-11-03. Polling detects observed additions, modifications and deletions on ONE volume. It does NOT observe reads, prove copying/exfiltration, or identify user/process. Run: .\USB-Drive-Monitoring.ps1 -DriveLetter E -DurationMinutes 1440 -OutputPath 'C:\Logs\USB-events.csv' Only local CSV output is written. Files on the monitored drive are not changed. #> [CmdletBinding()] param( [ValidatePattern('^[A-Za-z]$')][string]$DriveLetter, [ValidateRange(1,10080)][int]$DurationMinutes=1440, [ValidateRange(1,3600)][int]$PollSeconds=10, [ValidateRange(1,3600)][int]$WaitForDriveSeconds=300, [string]$OutputPath=(Join-Path (Get-Location) ('USB-Changes-' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff') + '.csv')) ) function Get-UsbContentSnapshot { param([string]$RootPath) try { $items = @(Get-ChildItem -LiteralPath $RootPath -File -Recurse -Force -ErrorAction Stop | ForEach-Object { [pscustomobject]@{Path=$_.FullName;Length=$_.Length;LastWriteTimeUtc=$_.LastWriteTimeUtc} }) [pscustomobject]@{Complete=$true;Items=$items;Error=$null} } catch { [pscustomobject]@{Complete=$false;Items=@();Error=$_.Exception.Message} } } function Compare-UsbSnapshots { param([AllowEmptyCollection()][object[]]$Previous=@(),[AllowEmptyCollection()][object[]]$Current=@()) $before=@{}; $after=@{} foreach ($item in $Previous) { $before[$item.Path]=$item } foreach ($item in $Current) { $after[$item.Path]=$item } $observed = [datetime]::UtcNow.ToString('o') foreach ($key in $after.Keys) { $kind = $null if (-not $before.ContainsKey($key)) { $kind='Created' } elseif ($before[$key].Length -ne $after[$key].Length -or $before[$key].LastWriteTimeUtc -ne $after[$key].LastWriteTimeUtc) { $kind='Modified' } if ($kind) { [pscustomobject][ordered]@{ObservedUtc=$observed;ChangeType=$kind;Path=$key;Length=$after[$key].Length;LastWriteTimeUtc=$after[$key].LastWriteTimeUtc.ToString('o');Details=''} } } foreach ($key in $before.Keys) { if (-not $after.ContainsKey($key)) { [pscustomobject][ordered]@{ObservedUtc=$observed;ChangeType='Deleted';Path=$key;Length=$before[$key].Length;LastWriteTimeUtc=$before[$key].LastWriteTimeUtc.ToString('o');Details='Absent from subsequent complete snapshot'} } } } function Assert-UsbLogLocation { param([string]$RootPath,[string]$OutputPath) $root = [IO.Path]::GetFullPath($RootPath).TrimEnd('\') + '\' $log = [IO.Path]::GetFullPath($OutputPath) if ($log.StartsWith($root,[StringComparison]::OrdinalIgnoreCase)) { throw 'Save the CSV outside the monitored drive to avoid recording its own writes.' } } function Write-UsbStatus { param([string]$OutputPath,[string]$ChangeType,[string]$RootPath,[string]$Details='') [pscustomobject][ordered]@{ObservedUtc=[datetime]::UtcNow.ToString('o');ChangeType=$ChangeType;Path=$RootPath;Length='';LastWriteTimeUtc='';Details=$Details} | Export-Csv -LiteralPath $OutputPath -Append -NoTypeInformation -Encoding UTF8 -ErrorAction Stop } function Invoke-UsbMonitor { [CmdletBinding()] param([string]$DriveLetter,[int]$DurationMinutes=1440,[int]$PollSeconds=10,[int]$WaitForDriveSeconds=300,[string]$OutputPath) $ErrorActionPreference='Stop' $waitDeadline = [datetime]::UtcNow.AddSeconds($WaitForDriveSeconds) $selected = $null do { $volumes = @(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=2' -ErrorAction Stop) if ($DriveLetter) { $selected = $volumes | Where-Object { $_.DeviceID -ieq "${DriveLetter}:" } | Select-Object -First 1 } elseif ($volumes.Count -gt 1) { throw 'Multiple removable drives detected. Select one with -DriveLetter.' } elseif ($volumes.Count -eq 1) { $selected=$volumes[0] } if (-not $selected) { if ([datetime]::UtcNow -ge $waitDeadline) { throw 'No matching removable drive appeared before WaitForDriveSeconds expired.' } Start-Sleep -Seconds 1 } } until ($selected) $root = $selected.DeviceID + '\' $serial = $selected.VolumeSerialNumber $outputFile=[IO.Path]::GetFullPath($OutputPath) Assert-UsbLogLocation -RootPath $root -OutputPath $outputFile [void](New-Item -Path $outputFile -ItemType File -ErrorAction Stop) '"ObservedUtc","ChangeType","Path","Length","LastWriteTimeUtc","Details"' | Set-Content -LiteralPath $outputFile -Encoding UTF8 -ErrorAction Stop $previous = Get-UsbContentSnapshot -RootPath $root if (-not $previous.Complete) { Write-UsbStatus -OutputPath $outputFile -ChangeType 'SnapshotFailed' -RootPath $root -Details $previous.Error throw 'Initial snapshot incomplete. No file-change conclusions were made.' } Write-UsbStatus -OutputPath $outputFile -ChangeType 'MonitoringStarted' -RootPath $root -Details "Baseline files: $($previous.Items.Count); volume serial: $serial" $deadline=[datetime]::UtcNow.AddMinutes($DurationMinutes) while ([datetime]::UtcNow -lt $deadline) { $remaining=($deadline-[datetime]::UtcNow).TotalSeconds if ($remaining -le 0) { break } Start-Sleep -Milliseconds ([int]([Math]::Min($PollSeconds,$remaining)*1000)) $currentVolume = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$($selected.DeviceID)'" -ErrorAction Stop if (-not $currentVolume -or $currentVolume.VolumeSerialNumber -ne $serial) { Write-UsbStatus -OutputPath $outputFile -ChangeType 'DisconnectedOrReplaced' -RootPath $root return [pscustomobject]@{Result='Disconnected or volume replaced';OutputPath=$outputFile} } $current=Get-UsbContentSnapshot -RootPath $root if (-not $current.Complete) { Write-UsbStatus -OutputPath $outputFile -ChangeType 'SnapshotFailed' -RootPath $root -Details $current.Error throw 'Snapshot incomplete. Stopped rather than treating unreadable files as deletions.' } $events=@(Compare-UsbSnapshots -Previous $previous.Items -Current $current.Items) if ($events.Count) { $events | Export-Csv -LiteralPath $outputFile -Append -NoTypeInformation -Encoding UTF8 -ErrorAction Stop } $previous=$current } Write-UsbStatus -OutputPath $outputFile -ChangeType 'DurationElapsed' -RootPath $root [pscustomobject]@{Result='Duration elapsed';OutputPath=$outputFile} } if ($MyInvocation.InvocationName -ne '.') { $invokeParameters=@{} + $PSBoundParameters $invokeParameters.OutputPath=$OutputPath Invoke-UsbMonitor @invokeParameters }