VigiDoc a product by SSHack

Free tool

USB device history on Windows: a free PowerShell script to list connected USB drives

Which USB drives have been plugged into this computer, and when? Get-UsbHistory answers in a single command, without installing or changing anything. This free script is written by SSHack, an offensive security firm and the publisher of VigiDoc, for system administrators, CISOs and SMB owners who need a fast answer to that question.

By the SSHack team · Published · Last updated · about 16 minutes to read (excluding the script)

In short

To see the USB history of a Windows computer, save the free Get-UsbHistory.ps1 script and run powershell -ExecutionPolicy Bypass -File .\Get-UsbHistory.ps1. It lists every USB flash drive, external disk or memory card ever connected, with its model, serial number, first install, last arrival and last removal. The script is read-only, needs no installation or module, and works without administrator rights (tested on Windows 11). It does not show the files copied to those drives, because Windows does not record them by default. The script's comments, help and output are in French; this page translates every label you will see.

What the script shows

Windows keeps a record of every USB storage device it has recognized: an entry created on first connection, dates updated each time the device is plugged in, the last drive letter assigned and the volume name. This information exists on every computer, but it is scattered across device properties, several registry keys and an event log. Get-UsbHistory pulls it into a single table, from the most recently connected device to the oldest.

It covers USB flash drives, external hard drives and SSDs (including those using UASP, a faster USB protocol that makes them appear as SCSI disks), memory card readers, USB CD/DVD drives and phones seen in file transfer mode (MTP).

It bundles several of the checks described step by step in our guide How to see what files an employee copied to a USB drive: the USBSTOR registry list, connection dates, event 1006, drive letters and user sessions. It does not read the setupapi.dev.log file, recent shortcuts or the Security log: those checks are still manual, following the guide.

What you get with each method
MethodAdministrator rightsConnection datesDrive letter and volume nameCopied files
Registry Editor, USBSTOR keyNot for the listNo: the subkey holding the dates is restricted to the SYSTEM accountMust be looked up by hand in two other keysNo
Device Manager, with hidden devices shownNoYes, one device at a time (Details tab)NoNo
Get-UsbHistory scriptNoYes, for all devices at once, plus the history from the Partition/Diagnostic logYes: last known letter and last known nameNo
Removable storage auditing (event 4663)Yes, to read the Security logNo: it records file accessNoPartly, and only if auditing was enabled before the fact

The script makes three commitments, which you can check by reading it:

A note on language

Get-UsbHistory was written for French-speaking administrators. Its comments, built-in help, output labels and two of its parameters (-Chronologie for the timeline, -Detail for all columns) are in French, and dates are printed day first (DD/MM/YYYY). The commands and the logic are the same in any language. The tables on this page translate each column and message you will see, and the link printed at the end of the output points to the French version of our guide on copied files; the English version is here.

Run the script in 4 steps

We do not distribute a .ps1 file for download: the full code is shown below so you can read it before you use it.

  1. Copy the script. In the section The full script, select the whole code block and copy it (Ctrl+C).
  2. Save it to a file. Open Windows PowerShell (Start menu, type "PowerShell"), without administrator rights. The two commands below move to your user folder, then write the clipboard contents to Get-UsbHistory.ps1 as UTF-8 with BOM: that is the encoding that keeps accented characters intact in Windows PowerShell 5.1.
    cd $env:USERPROFILE
    Get-Clipboard -Raw | Set-Content -Path .\Get-UsbHistory.ps1 -Encoding UTF8
    Prefer Notepad? Paste the code, choose "Save as", the "All files" type, the name Get-UsbHistory.ps1 and the "UTF-8 with BOM" encoding. If the file is saved without a BOM, the script still runs, but it shows a warning and accented characters come out garbled.
  3. Run it. In the same window, type:
    powershell -ExecutionPolicy Bypass -File .\Get-UsbHistory.ps1
    The scan takes a few seconds (under 6 seconds on our test machine).
  4. Keep a record if needed. Add -Csv followed by a path to save every column to a file that opens in Excel, for example -Csv .\usb.csv.

What the -ExecutionPolicy Bypass parameter does

The PowerShell execution policy decides whether a script is allowed to run. On a Windows client where no policy is set, the Restricted mode applies: commands typed one at a time are allowed, script files are refused. The -ExecutionPolicy Bypass parameter lifts this restriction for the single PowerShell session started by the command.

According to Microsoft's documentation, this parameter sets the policy of the new session, stores it in that process's $Env:PSExecutionPolicyPreference environment variable, and does not change the policy saved in the registry. When the window closes, nothing remains: the computer's configuration has not changed.

Two precautions

A policy enforced by GPO still takes precedence: if your organization requires signed scripts, the command will fail and you will need to sign the script with your internal certificate. More importantly, Microsoft points out that the execution policy is not a security boundary. The only real precaution, for this script as for any other, is to read it before running it.

Options

Get-UsbHistory.ps1 parameters
OptionEffect
-Csv <path>Saves every column to a CSV file (semicolon-separated, UTF-8 with BOM, readable by Excel). This is the script's only write.
-ChronologieAdds a timeline: every arrival and removal still present in the Partition/Diagnostic log, from oldest to newest. With -Csv, the timeline goes to a second file.
-DetailShows every column, device by device, instead of the summary table.
-PassThruAlso returns PowerShell objects, so you can sort or filter the results in another command.
Get-Help .\Get-UsbHistory.ps1 -FullShows the built-in help (in French) with examples; under the Restricted policy, first run powershell -ExecutionPolicy Bypass.

To also read the sessions of other users signed in to the computer, open Windows PowerShell with "Run as administrator". It is not needed for the rest of the collection.

Sample output

Here is the actual output of the script, captured on October 14, 2026 on our test machine (Windows 11 Pro, version 26H2), run without elevation with the -Chronologie option. The computer name and part of the serial numbers are masked, and the timeline, which has 55 lines, is truncated. The output is in French; the translation follows each block.

PS> powershell -ExecutionPolicy Bypass -File .\Get-UsbHistory.ps1 -Chronologie

Supports USB vus par le poste POSTE-TEST (relevé du 14/10/2026 14:38)

Dernière arrivée 1re installation Dernier retrait  Présent Volume Modèle              N° de série
---------------- ---------------- ---------------  ------- ------ ------              -----------
24/09/2026 11:08 24/09/2026 10:58 24/09/2026 12:04 Non     E: SD  Generic- SD/MMC     A000001XXXXXA8D3
11/09/2026 22:22 06/08/2026 16:25 -                Non     USB    USB SanDisk 3.2Gen1 00002801XXXXXXXX0610

Toutes les colonnes : relancez avec -Detail ou exportez avec -Csv <chemin>.

Translation: "USB devices seen by computer POSTE-TEST (collected 14/10/2026 14:38)". The columns are Last arrival, First install, Last removal, Present (Oui = yes, Non = no), Volume, Model and Serial number. The last line reads: "All columns: run again with -Detail or export with -Csv <path>."

Chronologie (journal Partition/Diagnostic, du plus ancien au plus récent)

Date                Événement Modèle              N° de série          Taille
----                --------- ------              -----------          ------
06/08/2026 16:25:28 Arrivée   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610 123,0 Go
06/08/2026 16:26:06 Retrait   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610
[... 39 lignes coupées ...]
11/09/2026 17:45:09 Arrivée   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610 123,0 Go
11/09/2026 18:11:21 Retrait   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610
11/09/2026 18:12:45 Arrivée   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610 123,0 Go
11/09/2026 18:13:28 Retrait   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610
11/09/2026 18:13:42 Arrivée   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610 123,0 Go
11/09/2026 18:13:56 Retrait   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610
11/09/2026 20:44:43 Arrivée   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610 123,0 Go
11/09/2026 20:54:11 Retrait   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610
11/09/2026 21:15:23 Arrivée   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610 123,0 Go
11/09/2026 22:20:29 Arrivée   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610 123,0 Go
11/09/2026 22:22:14 Arrivée   USB SanDisk 3.2Gen1 00002801XXXXXXXX0610 123,0 Go
24/09/2026 10:58:41 Arrivée   Generic- SD/MMC     A000001XXXXXA8D3     127,9 Go
24/09/2026 11:08:50 Arrivée   Generic- SD/MMC     A000001XXXXXA8D3     127,9 Go
24/09/2026 12:04:17 Retrait   Generic- SD/MMC     A000001XXXXXA8D3

Arrivée = support visible (taille connue) ; Retrait = support retiré ou lecteur vide.
Un même branchement peut produire plusieurs lignes : lisez-les comme des indices.

Translation: "Timeline (Partition/Diagnostic log, oldest to newest)", with the columns Date, Event, Model, Serial number and Size; "Arrivée" means arrival and "Retrait" means removal, and sizes use a decimal comma ("123,0 Go" is 123.0 GB). The footer says: "Arrival = device visible (size known); Removal = device removed or reader empty. A single connection can produce several lines: read them as clues."

Sources lues

Source                                           Etat
------                                           ----
Périphériques Plug and Play (Get-PnpDevice)      lu : 98 périphérique(s) examiné(s)
Registre MountedDevices (lettres)                lu : 2 lettre(s) reliée(s) à un périphérique
Registre Windows Portable Devices (noms)         lu : 2 nom(s) de volume
Registre MountPoints2 (votre session)            lu : 5 volume(s)
Registre MountPoints2 (autres sessions ouvertes) non lu : droits administrateur requis
Journal Partition/Diagnostic (événement 1006)    lu : 55 événement(s) USB, journal conservé depuis le 11/07/2026
WMI Win32_DiskDrive (supports branchés)          lu : 1 disque(s) branché(s)

Lancé sans droits administrateur : seule la colonne MonteDansSessionDe se limite à votre propre session.
Si une source indique « accès refusé », relancez PowerShell en tant qu'administrateur.
Les dates sont à l'heure locale de ce poste. Windows ne garde que la dernière arrivée et le dernier retrait.

À retenir : ce script montre les supports USB branchés sur ce poste, PAS les fichiers copiés dessus.
Windows n'enregistre pas les copies de fichiers par défaut : sans audit activé avant les faits
(événement 4663) ou outil dédié, la liste des fichiers copiés n'existe pas sur le poste.
En savoir plus : https://vigidoc.me/guides/copie-fichiers-cle-usb/

Translation: the "Sources read" block lists each source and its status ("lu" = read, "non lu : droits administrateur requis" = not read: administrator rights required). Here it read 98 Plug and Play devices, 2 drive letters linked to a device, 2 volume names, 5 volumes in your own MountPoints2 key, 55 USB events in the Partition/Diagnostic log (kept since 11/07/2026, that is July 11) and 1 connected disk. The closing lines say that without admin rights only the MonteDansSessionDe column is limited to your own session; that if a source reports "accès refusé" (access denied), you should rerun PowerShell as administrator; that dates are in the computer's local time and Windows only keeps the last arrival and last removal; and, as a reminder, that the script shows the USB devices connected to the computer, NOT the files copied to them, because Windows does not record file copies by default without auditing (event 4663) enabled before the fact or a dedicated tool.

What you can read from it:

What each column means

The first seven rows of the table below match the summary table; the others appear with -Detail and in the CSV file. Column names are shown as the script prints them, in French, followed by their meaning.

The columns, their source in Windows and their pitfalls
ColumnSource in WindowsWhat it showsGood to know
Dernière arrivée (last arrival)Property DEVPKEY_Device_LastArrivalDateThe last time the device was connected to this computerOverwritten at each connection: only the latest date is kept
1re installation (first install)Property DEVPKEY_Device_FirstInstallDateThe first installation of this device (this serial number) on this computerIt does not change with driver updates, but starts over if the device entry was deleted
Dernier retrait (last removal)Property DEVPKEY_Device_LastRemovalDateThe last time the device was removedEmpty when Windows has no removal date, as for the SanDisk drive in the example
Présent (present)Property DEVPKEY_Device_IsPresent"Oui" (yes) if the device is connected at collection timeFor a connected device, the letter and name shown are the current ones
VolumeWMI for a connected device; otherwise the MountedDevices and Windows Portable Devices registry keysThe last known drive letter and volume nameA letter only points to the last device that received it. For a disconnected external hard drive, the letter is often unknown
Modèle (model)Device name (FriendlyName)The manufacturer and model reported by the deviceUnbranded drives often report "Generic Flash Disk": rely on the serial number instead
N° de série (serial number)Device instance IDWhat tells apart two drives of the same modelIf the second character is "&", the number was generated by Windows and does not follow the drive from one computer to another. For a card reader, it is the reader's number, not the card's
SerieUnique (unique serial)Computed by the script"Oui" (yes) if the serial number comes from the device itself, "Non (attribué par Windows)" (no, assigned by Windows) otherwiseA Windows-assigned number does not follow the drive from one computer to another
IdInstance (instance ID)Full device instance IDThe device's Plug and Play path, as Windows records itHelps you find the device's entry in the registry and in Device Manager
TypeDevice classFlash drive or disk, UASP disk, card reader, CD/DVD drive, MTP phoneThe card reader is recognized by its name: this is an inference
VidPidID of the parent USB deviceThe USB vendor and product codes, for example 0781:55A3Useful to match the same model across computers
Taille (size)Partition/Diagnostic log, otherwise WMICapacity in billions of bytes, close to the label on the driveFile Explorer shows less (about 114 GB for 123 GB) because it counts in powers of 2. For a card reader, this is the card's size
ArriveesJournal, JournalPremier, JournalDernier (log arrivals, first, last)Microsoft-Windows-Partition/Diagnostic log, event 1006The number of arrivals still recorded in the log, and the first and last oneA single connection can produce several events; the log is overwritten when full
MonteDansSessionDe (mounted in session of)MountPoints2 registry key of each signed-in sessionThe accounts whose session saw the volumeWithout administrator rights, your session only. Accounts not signed in at collection time are not read
SourceComputed by the script"Windows (Plug and Play)", or "Journal seulement" (log only) when Windows has forgotten the device but the log still has itThese devices are marked "[journal]" in the summary table

Microsoft documents the DEVPKEY_Device_FirstInstallDate property. The other two date properties are defined in the Windows Driver Kit (file devpkey.h) without a dedicated documentation page: on our test machine, their values match the Partition/Diagnostic log events to the second.

With or without administrator rights

The script does not need to run as administrator. It goes through the Windows Plug and Play interface, which provides device dates to a standard user, even though the registry subkey where they are stored is restricted to the SYSTEM account. When a source is denied, it says so in the "Sources read" block (Sources lues) and carries on with the others.

What each source requires (checked on our Windows 11 test machine)
SourceWithout administrator rightsAs administrator
Device properties (dates, presence)ReadableReadable
MountedDevices and Windows Portable Devices registry keysReadable: the Users group has read accessReadable
Partition/Diagnostic logReadable from a session on the computer, not over a network connectionReadable
MountPoints2 registry keyYour session onlyAll sessions open at collection time
Properties registry subkey (raw dates)DeniedAlso denied (SYSTEM account only): the script does not need it
Security log (events 4663 and 6416)DeniedReadable, but the script does not read it

Limitations to keep in mind

This output is a starting point. Before drawing any conclusion, keep in mind what it cannot see.

What about copied files?

That is the question that almost always comes next: the drive was plugged in, but what was copied to it? On a Windows computer with default settings, that list does not exist. Microsoft's documentation on removable storage auditing is clear: an event is logged for each attempt to copy, move or save to a removable device when this policy setting is configured. So it must have been enabled before the fact, and you have to accept the volume of logs it produces.

Other traces, such as recent shortcuts or application Jump Lists, can show that a file was opened from the drive, not that it was copied there. Our guide How to see what files an employee copied to a USB drive explains what these traces prove and, above all, what they do not.

If the question comes up when someone is leaving, run the script as soon as the departure is announced, before the log is overwritten, export the result to CSV and file it with the rest of the security checklist for an employee's last 30 days. And if you are wondering whether to ban USB drives or monitor them, the guide Block or monitor USB drives? helps you decide based on your business.

The full script

Version 1.0.0 of October 14, 2026, published by SSHack under the MIT license (the license text is at the end of the script). The comments, help text and messages are in French, as published. To save and run it, follow the steps in Run the script in 4 steps.

<#
.SYNOPSIS
    Liste les supports de stockage USB (clés, disques, cartes mémoire) déjà branchés sur ce poste Windows.

.DESCRIPTION
    Get-UsbHistory rassemble les traces que Windows conserve sur les supports USB branchés sur le poste :
    modèle, numéro de série, date de première installation, de dernière arrivée et de dernier retrait,
    présence actuelle, dernière lettre de lecteur et dernier nom de volume connus, taille, et arrivées
    encore visibles dans le journal Microsoft-Windows-Partition/Diagnostic.

    Le script est en LECTURE SEULE : il n'écrit rien dans le registre, ne modifie aucune stratégie
    d'audit, n'installe rien et n'ouvre aucune connexion réseau. La seule écriture possible est le
    fichier CSV, et seulement si vous utilisez le paramètre -Csv.

    Il fonctionne sans droits administrateur sur Windows 10 et 11 (testé sur Windows 11). Lancé en administrateur, il lit en
    plus les sessions ouvertes des autres utilisateurs (colonne MonteDansSessionDe).

    IMPORTANT : le script montre les supports branchés, pas les fichiers copiés dessus.
    Windows n'enregistre pas les copies de fichiers par défaut.

.PARAMETER Csv
    Chemin du fichier CSV à créer (séparateur point-virgule, UTF-8 avec BOM : s'ouvre dans Excel).
    Toutes les colonnes y figurent. Un fichier existant du même nom est remplacé.

.PARAMETER Chronologie
    Affiche aussi chaque arrivée et chaque retrait de support encore présents dans le journal
    Microsoft-Windows-Partition/Diagnostic (événement 1006), du plus ancien au plus récent.
    Un même branchement peut y laisser plusieurs lignes : ce sont des indices, pas un compteur exact.
    Avec -Csv, la chronologie est exportée dans un second fichier, suffixé « -chronologie ».

.PARAMETER Detail
    Affiche toutes les colonnes, support par support, au lieu du tableau résumé.

.PARAMETER PassThru
    Renvoie aussi les résultats sous forme d'objets PowerShell, pour les trier ou les filtrer.

.EXAMPLE
    powershell -ExecutionPolicy Bypass -File .\Get-UsbHistory.ps1

    Affiche le tableau des supports USB, du plus récemment branché au plus ancien.

.EXAMPLE
    powershell -ExecutionPolicy Bypass -File .\Get-UsbHistory.ps1 -Csv C:\Temp\usb.csv

    Affiche le tableau et enregistre toutes les colonnes dans C:\Temp\usb.csv.

.EXAMPLE
    powershell -ExecutionPolicy Bypass -File .\Get-UsbHistory.ps1 -Chronologie

    Ajoute la liste de toutes les arrivées et de tous les retraits encore présents dans le journal.

.NOTES
    Nom      : Get-UsbHistory.ps1
    Auteur   : SSHack (https://sshack.me), éditeur du logiciel VigiDoc
    Version  : 1.0.0
    Date     : 2026-10-14
    Licence  : MIT (texte complet en fin de fichier)
    Testé    : Windows 11 Pro 26H2, Windows PowerShell 5.1, sans élévation

    Sources lues (toutes en lecture) :
    - Get-PnpDevice et Get-PnpDeviceProperty : DEVPKEY_Device_FirstInstallDate,
      DEVPKEY_Device_LastArrivalDate, DEVPKEY_Device_LastRemovalDate, DEVPKEY_Device_IsPresent ;
    - registre HKLM\SYSTEM\MountedDevices : dernière lettre de lecteur connue ;
    - registre HKLM\SOFTWARE\Microsoft\Windows Portable Devices\Devices : dernier nom de volume connu ;
    - registre ...\Explorer\MountPoints2 des sessions ouvertes : comptes dont la session a vu le volume ;
    - journal Microsoft-Windows-Partition/Diagnostic, événement 1006 : arrivées, retraits, taille ;
    - WMI Win32_DiskDrive : lettre, nom et taille des supports branchés en ce moment.

.LINK
    https://vigidoc.me/guides/historique-cle-usb-powershell/
#>

#Requires -Version 5.1

[CmdletBinding()]
param(
    [string]$Csv,
    [switch]$Chronologie,
    [switch]$Detail,
    [switch]$PassThru
)

# ---------------------------------------------------------------------------------------------
# 0. Vérifications préalables
# ---------------------------------------------------------------------------------------------

# Enregistré sans BOM, ce fichier est lu en ANSI par Windows PowerShell 5.1 et les accents
# s'affichent mal. Le test ci-dessous le détecte (message volontairement écrit sans accent).
if ('é'.Length -ne 1) {
    Write-Warning "Fichier enregistre sans BOM UTF-8 : les accents s'afficheront mal. Reenregistrez-le en 'UTF-8 avec BOM'."
}

$Invariant = [Globalization.CultureInfo]::InvariantCulture
$Identite  = [Security.Principal.WindowsIdentity]::GetCurrent()
$EstAdmin  = (New-Object Security.Principal.WindowsPrincipal($Identite)).IsInRole(
                 [Security.Principal.WindowsBuiltInRole]::Administrator)

# Bilan des sources lues, affiché à la fin
$Bilan = New-Object System.Collections.Generic.List[object]

# ---------------------------------------------------------------------------------------------
# 1. Fonctions utilitaires (aucune n'écrit quoi que ce soit)
# ---------------------------------------------------------------------------------------------

function Add-Bilan {
    param([string]$Source, [string]$Etat)
    $Bilan.Add([pscustomobject]@{ Source = $Source; Etat = $Etat })
}

# Traduit une erreur en motif lisible, en repérant les refus d'accès
function Get-MotifErreur {
    param($Erreur)
    $e = $Erreur.Exception
    while ($null -ne $e) {
        if ($e -is [System.Security.SecurityException] -or $e -is [System.UnauthorizedAccessException]) {
            return 'accès refusé : relancez PowerShell en tant qu''administrateur'
        }
        $e = $e.InnerException
    }
    return ('illisible : ' + $Erreur.Exception.Message)
}

# Ramène un identifiant de périphérique à une forme comparable d'une source à l'autre :
# « USBSTOR\DISK&VEN_X&PROD_Y\123&0 » (Plug and Play), « _??_USBSTOR#Disk&Ven_X&Prod_Y#123&0#{...} »
# (MountedDevices) et « SWD#WPDBUSENUM#_??_USBSTOR#... » (Windows Portable Devices) donnent la même clé.
function ConvertTo-Cle {
    param([string]$Texte)
    if ([string]::IsNullOrWhiteSpace($Texte)) { return '' }
    $t = $Texte.Trim([char]0).Trim().ToUpperInvariant()
    $t = $t -replace '^SWD[\\#]WPDBUSENUM[\\#]', ''
    $t = $t -replace '^(_\?\?_|\\\?\?\\|\\\\\?\\)', ''
    $t = $t -replace '#\{[0-9A-F-]{36}\}$', ''
    return ($t -replace '[\\/#]', '#')
}

# Numéro de série tiré de l'identifiant d'instance. Un « & » en deuxième position signale un
# identifiant fabriqué par Windows : le support n'a pas de numéro de série unique.
function Get-InfosSerie {
    param([string]$IdInstance)
    $dernier = ($IdInstance -split '\\')[-1]
    $serie   = $dernier -replace '&\d+$', ''      # USBSTOR ajoute « &0 » (numéro d'unité logique)
    $unique  = -not ($dernier.Length -gt 1 -and $dernier[1] -eq '&')
    return [pscustomobject]@{ Serie = $serie; Unique = $unique }
}

function Get-VidPid {
    param([string]$Id)
    if ($Id -match 'VID_([0-9A-F]{4})&PID_([0-9A-F]{4})') { return ('{0}:{1}' -f $Matches[1], $Matches[2]).ToUpperInvariant() }
    return ''
}

# « Kingston DataTraveler 3.0 USB Device » devient « Kingston DataTraveler 3.0 »
function Get-ModeleLisible {
    param([string]$Nom)
    if ([string]::IsNullOrWhiteSpace($Nom)) { return '' }
    $n = ($Nom -replace '\s+', ' ').Trim()
    return ($n -replace ' (USB|SCSI) (Disk )?Device$', '')
}

function Get-TypeSupport {
    param([string]$Id, [string]$Classe, [string]$Modele)
    if ($Classe -eq 'WPD')   { return 'Téléphone ou appareil MTP' }
    if ($Classe -eq 'CDROM') { return 'Lecteur CD/DVD USB' }
    if ($Modele -match 'SD/MMC|Card.?Reader|Multi.?Card|SDXC|micro ?SD|CF.?Card|xD-Picture') { return 'Lecteur de cartes' }
    if ($Id -like 'SCSI\*')  { return 'Disque USB (UASP)' }
    return 'Clé ou disque USB'
}

function Format-Date {
    param($Date, [string]$Modele = 'dd/MM/yyyy HH:mm')
    if ($Date -is [datetime] -and $Date.Year -gt 1601) { return $Date.ToString($Modele, $Invariant) }
    return ''
}

function Limit-Texte {
    param([string]$Texte, [int]$Max)
    if ([string]::IsNullOrEmpty($Texte)) { return '-' }
    if ($Texte.Length -le $Max) { return $Texte }
    return $Texte.Substring(0, $Max - 3) + '...'
}

function Format-Taille {
    param([UInt64]$Octets)
    if ($Octets -eq 0) { return '' }
    return ('{0:N1} Go' -f ($Octets / 1e9))
}

# Lit une sous-clé de HKLM ou HKU avec .NET (et non le lecteur HKLM:, qui prendrait le « / » de
# « SD/MMC » pour un séparateur). Ouverture en lecture seule.
function Open-CleRegistre {
    param([Microsoft.Win32.RegistryKey]$Racine, [string]$Chemin)
    return $Racine.OpenSubKey($Chemin, $false)
}

# ---------------------------------------------------------------------------------------------
# 2. Inventaire des périphériques connus de Windows
# ---------------------------------------------------------------------------------------------

$ClesPnp = @(
    'DEVPKEY_Device_FriendlyName',
    'DEVPKEY_Device_FirstInstallDate',
    'DEVPKEY_Device_LastArrivalDate',
    'DEVPKEY_Device_LastRemovalDate',
    'DEVPKEY_Device_Parent',
    'DEVPKEY_Device_IsPresent'
)

$Candidats = New-Object System.Collections.Generic.List[object]
$ModePnp = $true
try {
    $tous = @(Get-PnpDevice -ErrorAction Stop)
    foreach ($d in $tous) {
        $id = [string]$d.InstanceId
        if ($id -like 'USBSTOR\*' -or
            ($d.Class -eq 'DiskDrive' -and $id -like 'SCSI\*') -or
            ($d.Class -eq 'WPD' -and $id -like 'USB\*')) {
            $Candidats.Add([pscustomobject]@{ Id = $id; Classe = [string]$d.Class; Nom = [string]$d.FriendlyName })
        }
    }
    Add-Bilan 'Périphériques Plug and Play (Get-PnpDevice)' ('lu : {0} périphérique(s) examiné(s)' -f $tous.Count)
} catch {
    # Voie de secours : lecture directe de la clé USBSTOR (sans les dates, réservées au compte SYSTEM)
    $ModePnp = $false
    Add-Bilan 'Périphériques Plug and Play (Get-PnpDevice)' ((Get-MotifErreur $_) + ' ; lecture directe du registre USBSTOR')
    try {
        $usbstor = Open-CleRegistre ([Microsoft.Win32.Registry]::LocalMachine) 'SYSTEM\CurrentControlSet\Enum\USBSTOR'
        if ($null -ne $usbstor) {
            foreach ($famille in $usbstor.GetSubKeyNames()) {
                $kf = $usbstor.OpenSubKey($famille, $false)
                foreach ($inst in $kf.GetSubKeyNames()) {
                    $ki = $kf.OpenSubKey($inst, $false)
                    $classe = 'DiskDrive'
                    if ($famille -like 'CdRom*') { $classe = 'CDROM' }
                    $Candidats.Add([pscustomobject]@{ Id = ('USBSTOR\{0}\{1}' -f $famille, $inst).ToUpperInvariant(); Classe = $classe; Nom = [string]$ki.GetValue('FriendlyName') })
                    $ki.Close()
                }
                $kf.Close()
            }
            $usbstor.Close()
        }
        Add-Bilan 'Registre Enum\USBSTOR (secours)' ('lu : {0} support(s)' -f $Candidats.Count)
    } catch {
        Add-Bilan 'Registre Enum\USBSTOR (secours)' (Get-MotifErreur $_)
    }
}

# ---------------------------------------------------------------------------------------------
# 3. Dernière lettre connue (MountedDevices) : une lettre ne pointe que vers un seul support,
#    celui qui l'a reçue en dernier. Les disques USB « fixes » y sont décrits par une signature
#    binaire, non reliée ici à leur numéro de série : leur lettre reste alors inconnue.
# ---------------------------------------------------------------------------------------------

$LettreParCle  = @{}
$VolumesParCle = @{}
try {
    $md = Open-CleRegistre ([Microsoft.Win32.Registry]::LocalMachine) 'SYSTEM\MountedDevices'
    if ($null -eq $md) { throw 'clé absente' }
    foreach ($nom in $md.GetValueNames()) {
        $octets = $md.GetValue($nom)
        if (-not ($octets -is [byte[]]) -or $octets.Length -le 24) { continue }
        $texte = [Text.Encoding]::Unicode.GetString($octets).Trim([char]0)
        if ($texte -notmatch '^(_\?\?_|\\\?\?\\)') { continue }
        $cle = ConvertTo-Cle $texte
        if ($nom -match '^\\DosDevices\\([A-Za-z]:)$') {
            $LettreParCle[$cle] = $Matches[1].ToUpperInvariant()
        } elseif ($nom -match '^\\\?\?\\Volume(\{[0-9A-Fa-f-]{36}\})$') {
            if (-not $VolumesParCle.ContainsKey($cle)) { $VolumesParCle[$cle] = New-Object System.Collections.Generic.List[string] }
            $VolumesParCle[$cle].Add($Matches[1].ToLowerInvariant())
        }
    }
    $md.Close()
    Add-Bilan 'Registre MountedDevices (lettres)' ('lu : {0} lettre(s) reliée(s) à un périphérique' -f $LettreParCle.Count)
} catch {
    Add-Bilan 'Registre MountedDevices (lettres)' (Get-MotifErreur $_)
}

# ---------------------------------------------------------------------------------------------
# 4. Dernier nom de volume connu (Windows Portable Devices)
# ---------------------------------------------------------------------------------------------

$NomParCle = @{}
try {
    $wpd = Open-CleRegistre ([Microsoft.Win32.Registry]::LocalMachine) 'SOFTWARE\Microsoft\Windows Portable Devices\Devices'
    if ($null -ne $wpd) {
        foreach ($n in $wpd.GetSubKeyNames()) {
            $k = $wpd.OpenSubKey($n, $false)
            if ($null -eq $k) { continue }
            $fn = [string]$k.GetValue('FriendlyName')
            if ($fn) { $NomParCle[(ConvertTo-Cle $n)] = $fn }
            $k.Close()
        }
        $wpd.Close()
        Add-Bilan 'Registre Windows Portable Devices (noms)' ('lu : {0} nom(s) de volume' -f $NomParCle.Count)
    } else {
        Add-Bilan 'Registre Windows Portable Devices (noms)' 'clé absente'
    }
} catch {
    Add-Bilan 'Registre Windows Portable Devices (noms)' (Get-MotifErreur $_)
}

# ---------------------------------------------------------------------------------------------
# 5. Sessions qui ont vu le volume (MountPoints2). Sans droits administrateur : votre session
#    seulement. En administrateur : toutes les sessions ouvertes en ce moment. Les comptes
#    déconnectés ne sont pas lus (il faudrait charger leur ruche, donc écrire dans le registre).
# ---------------------------------------------------------------------------------------------

$SessionsParVolume = @{}
function Read-MountPoints2 {
    param([Microsoft.Win32.RegistryKey]$Ruche, [string]$Compte)
    $mp = Open-CleRegistre $Ruche 'Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2'
    if ($null -eq $mp) { return 0 }
    $n = 0
    foreach ($g in $mp.GetSubKeyNames()) {
        if ($g -match '^\{[0-9A-Fa-f-]{36}\}$') {
            $g = $g.ToLowerInvariant()
            if (-not $SessionsParVolume.ContainsKey($g)) { $SessionsParVolume[$g] = New-Object System.Collections.Generic.List[string] }
            if (-not $SessionsParVolume[$g].Contains($Compte)) { $SessionsParVolume[$g].Add($Compte) }
            $n++
        }
    }
    $mp.Close()
    return $n
}

$CompteCourant = '{0}\{1}' -f $env:USERDOMAIN, $env:USERNAME
try {
    $n = Read-MountPoints2 ([Microsoft.Win32.Registry]::CurrentUser) $CompteCourant
    Add-Bilan 'Registre MountPoints2 (votre session)' ('lu : {0} volume(s)' -f $n)
} catch {
    Add-Bilan 'Registre MountPoints2 (votre session)' (Get-MotifErreur $_)
}
if ($EstAdmin) {
    $autres = 0
    $refus  = 0
    foreach ($sid in [Microsoft.Win32.Registry]::Users.GetSubKeyNames()) {
        if ($sid -notmatch '^S-1-5-21-[\d-]+$' -or $sid -eq $Identite.User.Value) { continue }
        try {
            # Nom du compte lu dans la ruche elle-même : aucune requête vers un contrôleur de domaine
            $compte = $sid
            $ve = Open-CleRegistre ([Microsoft.Win32.Registry]::Users) "$sid\Volatile Environment"
            if ($null -ne $ve) {
                $u = [string]$ve.GetValue('USERNAME')
                if ($u) { $compte = '{0}\{1}' -f $ve.GetValue('USERDOMAIN'), $u }
                $ve.Close()
            }
            $ruche = Open-CleRegistre ([Microsoft.Win32.Registry]::Users) $sid
            [void](Read-MountPoints2 $ruche $compte)
            $ruche.Close()
            $autres++
        } catch {
            $refus++
        }
    }
    Add-Bilan 'Registre MountPoints2 (autres sessions ouvertes)' ('lu : {0} session(s), {1} refus' -f $autres, $refus)
} else {
    Add-Bilan 'Registre MountPoints2 (autres sessions ouvertes)' 'non lu : droits administrateur requis'
}

# ---------------------------------------------------------------------------------------------
# 6. Journal Microsoft-Windows-Partition/Diagnostic, événement 1006 (Windows 10 et 11).
#    Chaque événement décrit l'état du disque à un instant : taille > 0 quand le support devient
#    visible (arrivée), taille = 0 au retrait ou quand un lecteur de cartes est vide. Un même
#    branchement peut produire plusieurs événements : ce sont des indices, pas un compteur exact.
#    Le journal a une taille limitée : les événements les plus anciens sont écrasés.
# ---------------------------------------------------------------------------------------------

$Journal = New-Object System.Collections.Generic.List[object]
$JournalLisible = $false
$NomJournal = 'Microsoft-Windows-Partition/Diagnostic'
try {
    $evts = @(Get-WinEvent -LogName $NomJournal -FilterXPath '*[System[EventID=1006]]' -ErrorAction Stop)
    $JournalLisible = $true
    foreach ($ev in $evts) {
        # Tri rapide : on ne décode que les événements dont le parent est un périphérique USB
        $estUsb = $false
        foreach ($p in $ev.Properties) {
            if ($p.Value -is [string] -and $p.Value -like 'USB\VID_*') { $estUsb = $true; break }
        }
        if (-not $estUsb) { continue }
        $champs = @{}
        foreach ($donnee in ([xml]$ev.ToXml()).Event.EventData.Data) { $champs[[string]$donnee.Name] = [string]$donnee.InnerText }
        $capacite = [UInt64]0
        [void][UInt64]::TryParse($champs['Capacity'], [ref]$capacite)
        $evenement = 'Retrait'
        if ($capacite -gt 0) { $evenement = 'Arrivée' }
        $modele = (('{0} {1}' -f $champs['Manufacturer'], $champs['Model']) -replace '\bNULL\b', '' -replace '\s+', ' ').Trim()
        $Journal.Add([pscustomobject]@{
            Date       = $ev.TimeCreated
            Evenement  = $evenement
            Modele     = $modele
            Serie      = ([string]$champs['SerialNumber']).Trim()
            Parent     = [string]$champs['ParentId']
            CleParent  = ConvertTo-Cle $champs['ParentId']
            Capacite   = $capacite
        })
    }
    $plusAncien = $null
    try { $plusAncien = (Get-WinEvent -LogName $NomJournal -Oldest -MaxEvents 1 -ErrorAction Stop).TimeCreated } catch { }
    $depuis = ''
    if ($plusAncien) { $depuis = ', journal conservé depuis le ' + (Format-Date $plusAncien 'dd/MM/yyyy') }
    Add-Bilan 'Journal Partition/Diagnostic (événement 1006)' ('lu : {0} événement(s) USB{1}' -f $Journal.Count, $depuis)
} catch {
    if ($_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') {
        $JournalLisible = $true
        Add-Bilan 'Journal Partition/Diagnostic (événement 1006)' 'lu : aucun événement'
    } elseif ($_.FullyQualifiedErrorId -like 'NoMatchingLogsFound*') {
        Add-Bilan 'Journal Partition/Diagnostic (événement 1006)' 'absent (Windows 10 ou 11 requis)'
    } else {
        Add-Bilan 'Journal Partition/Diagnostic (événement 1006)' (Get-MotifErreur $_)
    }
}

# ---------------------------------------------------------------------------------------------
# 7. Supports branchés en ce moment : lettre, nom et taille réels (WMI, lecture seule)
# ---------------------------------------------------------------------------------------------

$PresentParCle = @{}
try {
    foreach ($disque in @(Get-CimInstance -ClassName Win32_DiskDrive -ErrorAction Stop)) {
        $lettres = New-Object System.Collections.Generic.List[string]
        $noms    = New-Object System.Collections.Generic.List[string]
        foreach ($part in @(Get-CimAssociatedInstance -InputObject $disque -ResultClassName Win32_DiskPartition -ErrorAction SilentlyContinue)) {
            foreach ($vol in @(Get-CimAssociatedInstance -InputObject $part -ResultClassName Win32_LogicalDisk -ErrorAction SilentlyContinue)) {
                $lettres.Add([string]$vol.DeviceID)
                if ($vol.VolumeName) { $noms.Add([string]$vol.VolumeName) }
            }
        }
        $taille = [UInt64]0
        if ($disque.Size) { $taille = [UInt64]$disque.Size }
        $PresentParCle[(ConvertTo-Cle $disque.PNPDeviceID)] = [pscustomobject]@{
            Lettres = ($lettres -join ' ')
            Noms    = ($noms -join ' / ')
            Taille  = $taille
        }
    }
    Add-Bilan 'WMI Win32_DiskDrive (supports branchés)' ('lu : {0} disque(s) branché(s)' -f $PresentParCle.Count)
} catch {
    Add-Bilan 'WMI Win32_DiskDrive (supports branchés)' (Get-MotifErreur $_)
}

# ---------------------------------------------------------------------------------------------
# 8. Assemblage : une ligne par support
# ---------------------------------------------------------------------------------------------

$Resultats = New-Object System.Collections.Generic.List[object]
$ParentsRattaches = @{}

# Événements du journal qui concernent un support donné (par parent USB, sinon par numéro de série)
function Get-EvenementsDuSupport {
    param([string]$CleParent, [string]$Serie, [bool]$SerieUnique)
    $liste = @()
    if ($CleParent) { $liste = @($Journal | Where-Object { $_.CleParent -eq $CleParent }) }
    if ($liste.Count -eq 0 -and $SerieUnique -and $Serie.Length -ge 6) {
        $liste = @($Journal | Where-Object { $_.Serie -eq $Serie })
    }
    return ,$liste
}

foreach ($c in $Candidats) {
    $prop = @{}
    if ($ModePnp) {
        try {
            foreach ($p in @(Get-PnpDeviceProperty -InstanceId $c.Id -KeyName $ClesPnp -ErrorAction Stop)) {
                # Une propriété absente (ex. : jamais retiré) revient sans champ Data
                $valeur = $null
                if ($p.PSObject.Properties['Data']) { $valeur = $p.Data }
                $prop[[string]$p.KeyName] = $valeur
            }
        } catch { }
    }
    $parent = [string]$prop['DEVPKEY_Device_Parent']

    # Un disque SCSI n'est retenu que s'il est branché derrière un port USB (protocole UASP)
    if ($c.Id -like 'SCSI\*' -and $parent -notlike 'USB\*') { continue }

    $nom = [string]$prop['DEVPKEY_Device_FriendlyName']
    if (-not $nom) { $nom = $c.Nom }
    $modele = Get-ModeleLisible $nom

    # Numéro de série : celui de l'instance, sinon celui du périphérique USB parent
    $infos = Get-InfosSerie $c.Id
    if (-not $infos.Unique -and $parent -like 'USB\VID*') {
        $infosParent = Get-InfosSerie $parent
        if ($infosParent.Unique) { $infos = $infosParent }
    }

    $cle       = ConvertTo-Cle $c.Id
    $cleParent = ConvertTo-Cle $parent
    $present   = ($prop['DEVPKEY_Device_IsPresent'] -eq $true)

    # Journal : nombre d'arrivées, première et dernière
    $evs = Get-EvenementsDuSupport $cleParent $infos.Serie $infos.Unique
    foreach ($e in $evs) { $ParentsRattaches[$e.CleParent] = $true }
    $arrivees = @($evs | Where-Object { $_.Evenement -eq 'Arrivée' } | Sort-Object Date)
    $nbJournal = ''
    if ($JournalLisible) { $nbJournal = $arrivees.Count }
    $journalPremier = $null; $journalDernier = $null; $capacite = [UInt64]0
    if ($arrivees.Count -gt 0) {
        $journalPremier = $arrivees[0].Date
        $journalDernier = $arrivees[-1].Date
        $capacite       = $arrivees[-1].Capacite
    }

    # Lettre, nom de volume et taille
    $lettre = ''; $nomVolume = ''
    if ($present -and $PresentParCle.ContainsKey($cle)) {
        $lettre    = $PresentParCle[$cle].Lettres
        $nomVolume = $PresentParCle[$cle].Noms
        if ($capacite -eq 0) { $capacite = $PresentParCle[$cle].Taille }
    }
    if (-not $lettre -and $LettreParCle.ContainsKey($cle)) { $lettre = $LettreParCle[$cle] }
    if (-not $nomVolume -and $NomParCle.ContainsKey($cle)) { $nomVolume = $NomParCle[$cle] }
    if (-not $nomVolume -and $NomParCle.ContainsKey($cleParent)) { $nomVolume = $NomParCle[$cleParent] }

    # Comptes dont la session a vu l'un des volumes de ce support
    $comptes = New-Object System.Collections.Generic.List[string]
    if ($VolumesParCle.ContainsKey($cle)) {
        foreach ($g in $VolumesParCle[$cle]) {
            if ($SessionsParVolume.ContainsKey($g)) {
                foreach ($x in $SessionsParVolume[$g]) { if (-not $comptes.Contains($x)) { $comptes.Add($x) } }
            }
        }
    }

    $serieUnique = 'Non (attribué par Windows)'
    if ($infos.Unique) { $serieUnique = 'Oui' }
    $presentTexte = 'Non'
    if ($present) { $presentTexte = 'Oui' } elseif (-not $ModePnp) { $presentTexte = '?' }

    $Resultats.Add([pscustomobject]@{
        Type                 = Get-TypeSupport $c.Id $c.Classe $modele
        Modele               = $modele
        NumeroSerie          = $infos.Serie
        SerieUnique          = $serieUnique
        VidPid               = Get-VidPid $(if ($parent) { $parent } else { $c.Id })
        PremiereInstallation = $prop['DEVPKEY_Device_FirstInstallDate']
        DerniereArrivee      = $prop['DEVPKEY_Device_LastArrivalDate']
        DernierRetrait       = $prop['DEVPKEY_Device_LastRemovalDate']
        Present              = $presentTexte
        Lettre               = $lettre
        NomVolume            = $nomVolume
        Taille               = Format-Taille $capacite
        ArriveesJournal      = $nbJournal
        JournalPremier       = $journalPremier
        JournalDernier       = $journalDernier
        MonteDansSessionDe   = ($comptes -join ', ')
        Source               = 'Windows (Plug and Play)'
        IdInstance           = $c.Id
    })
}

# Supports présents dans le journal mais plus connus de Windows (entrée supprimée depuis)
$orphelins = @($Journal | Where-Object { -not $ParentsRattaches.ContainsKey($_.CleParent) } | Group-Object CleParent)
foreach ($groupe in $orphelins) {
    $evs = @($groupe.Group | Sort-Object Date)
    $arrivees = @($evs | Where-Object { $_.Evenement -eq 'Arrivée' })
    $retraits = @($evs | Where-Object { $_.Evenement -eq 'Retrait' })
    $infos = Get-InfosSerie $evs[-1].Parent
    $derniereArrivee = $null; $premiereArrivee = $null; $capacite = [UInt64]0
    if ($arrivees.Count -gt 0) {
        $premiereArrivee = $arrivees[0].Date
        $derniereArrivee = $arrivees[-1].Date
        $capacite        = $arrivees[-1].Capacite
    }
    $dernierRetrait = $null
    if ($retraits.Count -gt 0) { $dernierRetrait = $retraits[-1].Date }
    $serie = $evs[-1].Serie
    if (-not $serie) { $serie = $infos.Serie }
    $serieUnique = 'Non (attribué par Windows)'
    if ($infos.Unique) { $serieUnique = 'Oui' }
    $Resultats.Add([pscustomobject]@{
        Type                 = Get-TypeSupport '' 'DiskDrive' $evs[-1].Modele
        Modele               = $evs[-1].Modele
        NumeroSerie          = $serie
        SerieUnique          = $serieUnique
        VidPid               = Get-VidPid $evs[-1].Parent
        PremiereInstallation = $null
        DerniereArrivee      = $derniereArrivee
        DernierRetrait       = $dernierRetrait
        Present              = 'Non'
        Lettre               = ''
        NomVolume            = ''
        Taille               = Format-Taille $capacite
        ArriveesJournal      = $arrivees.Count
        JournalPremier       = $premiereArrivee
        JournalDernier       = $derniereArrivee
        MonteDansSessionDe   = ''
        Source               = 'Journal seulement (entrée Windows supprimée)'
        IdInstance           = $evs[-1].Parent
    })
}

# Tri : du plus récemment branché au plus ancien
$Resultats = @($Resultats | Sort-Object -Descending -Property @{ Expression = {
    $d = $_.DerniereArrivee
    if (-not ($d -is [datetime])) { $d = $_.JournalDernier }
    if ($d -is [datetime]) { $d } else { [datetime]::MinValue }
} })

# ---------------------------------------------------------------------------------------------
# 9. Affichage
# ---------------------------------------------------------------------------------------------

Write-Host ''
Write-Host ('Supports USB vus par le poste {0} (relevé du {1})' -f $env:COMPUTERNAME, (Get-Date).ToString('dd/MM/yyyy HH:mm', $Invariant)) -ForegroundColor Cyan

if ($Resultats.Count -eq 0) {
    Write-Host ''
    Write-Host 'Aucun support de stockage USB trouvé sur ce poste.' -ForegroundColor Green
    Write-Host 'Soit aucun support n''y a été branché, soit ses traces ont été supprimées (nettoyage, réinstallation).'
} elseif ($Detail) {
    $Resultats | Select-Object Type, Modele, NumeroSerie, SerieUnique, VidPid,
        @{ n = 'PremiereInstallation'; e = { Format-Date $_.PremiereInstallation } },
        @{ n = 'DerniereArrivee';      e = { Format-Date $_.DerniereArrivee } },
        @{ n = 'DernierRetrait';       e = { Format-Date $_.DernierRetrait } },
        Present, Lettre, NomVolume, Taille, ArriveesJournal,
        @{ n = 'JournalPremier'; e = { Format-Date $_.JournalPremier } },
        @{ n = 'JournalDernier'; e = { Format-Date $_.JournalDernier } },
        MonteDansSessionDe, Source, IdInstance | Format-List | Out-Host
} else {
    $Resultats | Select-Object `
        @{ n = 'Dernière arrivée'; e = { Limit-Texte (Format-Date $_.DerniereArrivee) 16 } },
        @{ n = '1re installation'; e = { Limit-Texte (Format-Date $_.PremiereInstallation) 16 } },
        @{ n = 'Dernier retrait';  e = { Limit-Texte (Format-Date $_.DernierRetrait) 16 } },
        @{ n = 'Présent';          e = { $_.Present } },
        @{ n = 'Volume';           e = { Limit-Texte (('{0} {1}' -f $_.Lettre, $_.NomVolume).Trim()) 14 } },
        @{ n = 'Modèle';           e = {
            $m = $_.Modele
            if ($_.Type -like 'Téléphone*') { $m = $m + ' [MTP]' }
            if ($_.Source -like 'Journal*') { $m = $m + ' [journal]' }
            Limit-Texte $m 24 } },
        @{ n = 'N° de série';      e = { Limit-Texte $_.NumeroSerie 20 } } |
        Format-Table -AutoSize | Out-Host
    Write-Host 'Toutes les colonnes : relancez avec -Detail ou exportez avec -Csv <chemin>.' -ForegroundColor DarkGray
}

# Chronologie des arrivées et retraits encore présents dans le journal
$LignesChrono = @($Journal | Sort-Object Date)
if ($Chronologie) {
    Write-Host ''
    Write-Host 'Chronologie (journal Partition/Diagnostic, du plus ancien au plus récent)' -ForegroundColor Cyan
    if ($LignesChrono.Count -eq 0) {
        Write-Host 'Aucun événement USB dans le journal (journal vide, illisible ou déjà écrasé).'
    } else {
        $LignesChrono | Select-Object `
            @{ n = 'Date';        e = { Format-Date $_.Date 'dd/MM/yyyy HH:mm:ss' } },
            @{ n = 'Événement';   e = { $_.Evenement } },
            @{ n = 'Modèle';      e = { Limit-Texte $_.Modele 30 } },
            @{ n = 'N° de série'; e = { Limit-Texte $_.Serie 22 } },
            @{ n = 'Taille';      e = { Format-Taille $_.Capacite } } | Format-Table -AutoSize | Out-Host
        Write-Host 'Arrivée = support visible (taille connue) ; Retrait = support retiré ou lecteur vide.' -ForegroundColor DarkGray
        Write-Host 'Un même branchement peut produire plusieurs lignes : lisez-les comme des indices.' -ForegroundColor DarkGray
    }
}

# Export CSV : seule écriture du script, et seulement sur demande
if ($Csv) {
    try {
        $chemin = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Csv)
        $dossier = Split-Path -Path $chemin -Parent
        if ($dossier -and -not (Test-Path -LiteralPath $dossier -PathType Container)) {
            throw ('le dossier {0} n''existe pas' -f $dossier)
        }
        $encodage = 'UTF8'
        if ($PSVersionTable.PSVersion.Major -ge 6) { $encodage = 'utf8BOM' }
        $Resultats | Select-Object Type, Modele, NumeroSerie, SerieUnique, VidPid,
            @{ n = 'PremiereInstallation'; e = { Format-Date $_.PremiereInstallation 'yyyy-MM-dd HH:mm:ss' } },
            @{ n = 'DerniereArrivee';      e = { Format-Date $_.DerniereArrivee 'yyyy-MM-dd HH:mm:ss' } },
            @{ n = 'DernierRetrait';       e = { Format-Date $_.DernierRetrait 'yyyy-MM-dd HH:mm:ss' } },
            Present, Lettre, NomVolume, Taille, ArriveesJournal,
            @{ n = 'JournalPremier'; e = { Format-Date $_.JournalPremier 'yyyy-MM-dd HH:mm:ss' } },
            @{ n = 'JournalDernier'; e = { Format-Date $_.JournalDernier 'yyyy-MM-dd HH:mm:ss' } },
            MonteDansSessionDe, Source, IdInstance |
            Export-Csv -LiteralPath $chemin -Delimiter ';' -NoTypeInformation -Encoding $encodage
        Write-Host ('Export CSV : {0}' -f $chemin) -ForegroundColor Green
        if ($Chronologie) {
            $cheminChrono = [IO.Path]::Combine([IO.Path]::GetDirectoryName($chemin),
                [IO.Path]::GetFileNameWithoutExtension($chemin) + '-chronologie' + [IO.Path]::GetExtension($chemin))
            $LignesChrono | Select-Object `
                @{ n = 'Date';        e = { Format-Date $_.Date 'yyyy-MM-dd HH:mm:ss' } },
                Evenement, Modele,
                @{ n = 'NumeroSerie'; e = { $_.Serie } },
                @{ n = 'Taille';      e = { Format-Taille $_.Capacite } },
                @{ n = 'IdParent';    e = { $_.Parent } } |
                Export-Csv -LiteralPath $cheminChrono -Delimiter ';' -NoTypeInformation -Encoding $encodage
            Write-Host ('Export CSV : {0}' -f $cheminChrono) -ForegroundColor Green
        }
    } catch {
        Write-Warning ('Export CSV impossible : ' + $_.Exception.Message)
    }
}

# Bilan des sources et droits
Write-Host ''
Write-Host 'Sources lues' -ForegroundColor Cyan
$Bilan | Format-Table -AutoSize -Wrap | Out-Host
if ($EstAdmin) {
    Write-Host 'Lancé en administrateur : les sessions ouvertes des autres utilisateurs ont aussi été lues.'
} else {
    Write-Host 'Lancé sans droits administrateur : seule la colonne MonteDansSessionDe se limite à votre propre session.'
    Write-Host 'Si une source indique « accès refusé », relancez PowerShell en tant qu''administrateur.'
}
Write-Host 'Les dates sont à l''heure locale de ce poste. Windows ne garde que la dernière arrivée et le dernier retrait.'

Write-Host ''
Write-Host 'À retenir : ce script montre les supports USB branchés sur ce poste, PAS les fichiers copiés dessus.' -ForegroundColor Yellow
Write-Host 'Windows n''enregistre pas les copies de fichiers par défaut : sans audit activé avant les faits' -ForegroundColor Yellow
Write-Host '(événement 4663) ou outil dédié, la liste des fichiers copiés n''existe pas sur le poste.' -ForegroundColor Yellow
Write-Host 'En savoir plus : https://vigidoc.me/guides/copie-fichiers-cle-usb/' -ForegroundColor Yellow
Write-Host ''

if ($PassThru) { $Resultats }

<#
Licence MIT

Copyright (c) 2026 SSHack

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#>

The script shows which drives were connected; VigiDoc shows what was copied to them

Get-UsbHistory tells you which drive was connected and when. VigiDoc adds what Windows does not keep: for each USB drive or disk inserted (letter, name, size, serial number), the list of files copied or overwritten on it, with the time, and an encrypted copy of each file on your own server. Keywords you choose trigger an alert in the Dashboard, without blocking anything.

VigiDoc only sees what happens after it is installed, and it only tracks devices that get a drive letter (flash drives, external disks and SSDs), not phones connected in MTP mode. So the time to install it is before the next departure: the 30-day trial starts as soon as the server is installed, with no license to request.

Frequently asked questions

How do I see the history of USB drives connected to a Windows PC?

Save the free Get-UsbHistory.ps1 script, then run it in Windows PowerShell with the -ExecutionPolicy Bypass option. It lists every USB storage device the computer knows, with its model, serial number, first install date, last arrival date and last removal date. Without the script, Device Manager shows the same dates one device at a time, once hidden devices are displayed.

Does the script show which files were copied to the drive?

No. By default, Windows does not log file copies to a USB drive: removable storage auditing must have been enabled before the fact, or a dedicated tool must have been in place. The script shows which drives were connected and when, which tells you where to focus the rest of the investigation.

Do I need administrator rights to run the script?

No. On our Windows 11 test machine, every source the script uses, dates included, can be read from a non-elevated session. Run as administrator, it also reads the sessions of other signed-in users, to show which accounts saw each volume.

Is the -ExecutionPolicy Bypass option risky?

It does not change the computer's configuration: it applies only to the PowerShell session started by the command and is gone when that session closes. It does, however, let the script run without any signature check, hence the basic rule: read a script before you run it. A policy enforced by GPO still takes precedence.

Why doesn't a drive I know was connected show up?

Its entry may have been removed: the device was uninstalled, a cleanup tool was run, or the computer was reinstalled or reimaged. The Partition/Diagnostic log, which the script also reads, may have been overwritten once full. Finally, a phone connected in file transfer mode is not a USB drive: it appears as an MTP device, with no drive letter.

Can the output be used as evidence against an employee?

It is a technical clue: it shows that a device was connected, not what was copied or who did it. Export it to CSV with the date of the collection and get advice from a lawyer before using it. Monitoring workstations also requires informing employees beforehand and keeping the approach proportionate (in France, under the Labor Code and the guidance of the CNIL, the national data protection authority); check your local employment law.

Sources