# Diagnostic APINETWORK pour Windows 8, 8.1, 10 et 11 (PowerShell 3.0 et plus). # Lecture seule : écrit seulement son rapport JSON dans le dossier courant. Licence MIT. # Syntaxe de PowerShell 3.0 seulement : ni classe, ni ::new(), ni opérateur ternaire. param([string]$Sortie = '') $ErrorActionPreference = 'SilentlyContinue' $VersionCollecteur = '1.1.0' $T0 = Get-Date if (-not $Sortie) { $Sortie = 'rapport-diagnostic-windows-' + (Get-Date).ToUniversalTime().ToString('yyyyMMdd-HHmmss') + '.json' } Write-Host "Diagnostic APINETWORK $VersionCollecteur : lecture seule, aucune modification du système." function Cim($Classe, $Ns = 'root\cimv2', $Filtre = $null) { try { if ($Filtre) { @(Get-CimInstance -ClassName $Classe -Namespace $Ns -Filter $Filtre -ErrorAction Stop) } else { @(Get-CimInstance -ClassName $Classe -Namespace $Ns -ErrorAction Stop) } } catch { if ($_.Exception.HResult -eq -2147024891 -or "$($_.Exception.Message)" -match 'denied|refus') { $script:Refus = $true } @() } } function Reg($Chemin, $Nom) { try { (Get-ItemProperty -Path $Chemin -Name $Nom -ErrorAction Stop).$Nom } catch { $null } } function Txt($v) { if ($null -eq $v) { return $null }; $s = "$v".Trim(); if ($s) { $s } else { $null } } function Iso($d) { if ($d -is [datetime]) { $d.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') } else { $null } } function Sec($o, $Statut, $Note = $null, $Sautes = $null) { $o['statut'] = $Statut if ($Note) { $o['note'] = $Note } elseif ($Statut -eq 'non_disponible') { $o['note'] = 'non disponible sur ce système' } if ($Sautes -and $Sautes.Count) { $o['sautes'] = @($Sautes) } $o } function Saute($Liste, $Element, $Raison) { [void]$Liste.Add([ordered]@{ element = $Element; raison = $Raison }) } function MacPrefixe($m) { if ("$m" -match '^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$') { $m.Substring(0, 8).Replace('-', ':').ToLower() + ':xx:xx:xx' } else { $null } } function DevId($s) { if (-not $s) { return $null }; $a = "$s".Split('\'); if ($a.Count -gt 1) { $a[0] + '\' + $a[1] } else { $a[0] } } function Arr($x) { , @($x | Where-Object { $null -ne $_ }) } $Admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $S = [ordered]@{} $OS = Cim Win32_OperatingSystem | Select-Object -First 1 $CS = Cim Win32_ComputerSystem | Select-Object -First 1 $Build = [int]("0" + $OS.BuildNumber) $SysDrive = "$env:SystemDrive".ToUpper() $CV = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' # ---------- machine ---------- Write-Host 'Machine...' $o = [ordered]@{} $Bios = Cim Win32_BIOS | Select-Object -First 1 $Enc = Cim Win32_SystemEnclosure | Select-Object -First 1 $o.fabricant = Txt $CS.Manufacturer $o.modele = Txt $CS.Model $o.identifiant_modele = Txt $CS.SystemFamily $c = @($Enc.ChassisTypes)[0] $ty = 'inconnu' if (@(8, 9, 10, 11, 14, 30, 31, 32) -contains $c -or $CS.PCSystemType -eq 2) { $ty = 'portable' } elseif (@(3, 4, 5, 6, 7, 15, 16, 35, 36) -contains $c) { $ty = 'bureau' } elseif ($c -eq 13) { $ty = 'tout_en_un' } elseif (@(17, 23, 28, 29) -contains $c -or @(4, 5, 7) -contains $CS.PCSystemType) { $ty = 'serveur' } $virt = $null if ("$($CS.Manufacturer) $($CS.Model)" -match 'VMware|VirtualBox|Virtual Machine|KVM|QEMU|Xen|Parallels|Hyper-V|innotek') { $virt = Txt $CS.Model; $ty = 'virtuelle' } $o.type = $ty $o.virtualisation = $virt $fwt = "$env:firmware_type" if ($fwt -eq 'UEFI') { $o.micrologiciel_type = 'uefi' } elseif ($fwt -eq 'Legacy') { $o.micrologiciel_type = 'bios' } else { $o.micrologiciel_type = 'inconnu' } $o.micrologiciel_version = Txt $Bios.SMBIOSBIOSVersion $o.micrologiciel_date = Iso $Bios.ReleaseDate $S.machine = Sec $o $(if ($o.fabricant -or $o.modele) { 'releve' } else { 'non_disponible' }) # ---------- systeme ---------- Write-Host 'Système...' $o = [ordered]@{} $dv = Reg $CV DisplayVersion; if (-not $dv) { $dv = Reg $CV ReleaseId } $ubr = Reg $CV UBR $o.nom = Txt $OS.Caption $o.version = Txt $OS.Version $o.build = $(if ($null -ne $ubr) { "$($OS.BuildNumber).$ubr" } else { Txt $OS.BuildNumber }) $o.edition = Txt ("$($OS.Caption) $dv") $o.distribution_id = 'windows' $o.distribution_famille = 'windows' $o.architecture = Txt $(if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }) $o.bits = $(if ("$($OS.OSArchitecture)" -match '64') { 64 } else { 32 }) $o.noyau = "NT $($OS.Version)" $o.installe_le = Iso $OS.InstallDate $o.demarre_le = Iso $OS.LastBootUpTime $o.duree_fonctionnement_s = $(if ($OS.LastBootUpTime) { [int64]((Get-Date) - $OS.LastBootUpTime).TotalSeconds } else { $null }) $o.fin_support = $null $S.systeme = Sec $o $(if ($OS) { 'releve' } else { 'non_disponible' }) # ---------- processeur ---------- Write-Host 'Processeur...' $o = [ordered]@{} $cpus = Cim Win32_Processor $o.modele = Txt (@($cpus)[0].Name) $o.architecture = Txt $env:PROCESSOR_ARCHITECTURE $o.coeurs = ($cpus | Measure-Object -Property NumberOfCores -Sum).Sum $o.threads = ($cpus | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum $o.frequence_mhz = @($cpus)[0].MaxClockSpeed $o.charge_pct = [math]::Round(($cpus | Measure-Object -Property LoadPercentage -Average).Average) $o.charge_1min = $null $pi = Cim Win32_PerfFormattedData_Counters_ProcessorInformation 'root\cimv2' "Name='_Total'" | Select-Object -First 1 $o.bridage_thermique_pct = $null if ($pi -and $null -ne $pi.PercentofMaximumFrequency -and $pi.PercentofMaximumFrequency -gt 0 -and $pi.PercentofMaximumFrequency -lt 100 -and $o.charge_pct -ge 50) { $o.bridage_thermique_pct = 100 - $pi.PercentofMaximumFrequency } $S.processeur = Sec $o $(if ($cpus.Count) { 'releve' } else { 'non_disponible' }) # ---------- memoire ---------- Write-Host 'Mémoire...' $o = [ordered]@{} $o.total_mo = [math]::Round($OS.TotalVisibleMemorySize / 1024) $o.disponible_mo = [math]::Round($OS.FreePhysicalMemory / 1024) $o.utilisee_pct = $(if ($OS.TotalVisibleMemorySize) { [math]::Round(100 * ($OS.TotalVisibleMemorySize - $OS.FreePhysicalMemory) / $OS.TotalVisibleMemorySize, 1) } else { $null }) $pf = Cim Win32_PageFileUsage $o.echange_total_mo = $(if ($pf.Count) { ($pf | Measure-Object -Property AllocatedBaseSize -Sum).Sum } else { $null }) $o.echange_utilise_mo = $(if ($pf.Count) { ($pf | Measure-Object -Property CurrentUsage -Sum).Sum } else { $null }) $types = @{ 20 = 'DDR'; 21 = 'DDR2'; 22 = 'DDR2 FB-DIMM'; 24 = 'DDR3'; 26 = 'DDR4'; 34 = 'DDR5'; 35 = 'LPDDR5'; 30 = 'LPDDR4' } $o.modules = Arr (Cim Win32_PhysicalMemory | ForEach-Object { $mt = $_.SMBIOSMemoryType; if (-not $mt) { $mt = $_.MemoryType } [ordered]@{ capacite_mo = [math]::Round($_.Capacity / 1MB); type = $types[[int]$mt]; vitesse_mhz = $_.Speed; emplacement = Txt $_.DeviceLocator } }) $S.memoire = Sec $o $(if ($OS) { 'releve' } else { 'non_disponible' }) # ---------- disques ---------- Write-Host 'Disques et santé SMART...' $o = [ordered]@{}; $sa = New-Object System.Collections.ArrayList $pd = @(Get-PhysicalDisk -ErrorAction SilentlyContinue) $dd = Cim Win32_DiskDrive $liste = New-Object System.Collections.ArrayList if ($pd.Count) { foreach ($d in $pd) { $ty = 'inconnu' if ("$($d.BusType)" -eq 'NVMe') { $ty = 'nvme' } elseif ("$($d.MediaType)" -eq 'SSD') { $ty = 'ssd' } elseif ("$($d.MediaType)" -eq 'HDD') { $ty = 'hdd' } if (@('USB', 'SD', 'MMC') -contains "$($d.BusType)") { $ty = 'amovible' } if ("$($d.FriendlyName)" -match 'Virtual|VMware|VBOX|QEMU|Msft Virtual') { $ty = 'virtuel' } $h = "$($d.HealthStatus)" $sm = [ordered]@{ statut = $(if ($h -eq 'Healthy') { 'ok' } elseif ($h -eq 'Warning' -or $h -eq 'Unhealthy') { 'defaut' } else { 'inconnu' }); source = 'Get-PhysicalDisk' } if ($Admin) { $rc = $d | Get-StorageReliabilityCounter -ErrorAction SilentlyContinue if ($rc) { $sm.source = 'Get-StorageReliabilityCounter' $sm.heures = $rc.PowerOnHours; $sm.usure_pct = $rc.Wear; $sm.temperature_c = $(if ($rc.Temperature) { $rc.Temperature } else { $null }) $sm.erreurs_media = $rc.ReadErrorsUncorrected } } [void]$liste.Add([ordered]@{ nom = "PhysicalDrive$($d.DeviceId)"; modele = Txt $d.FriendlyName; type = $ty; bus = Txt $d.BusType taille_go = [math]::Round($d.Size / 1e9); interne = $ty -ne 'amovible'; smart = $sm }) } } else { foreach ($d in $dd) { $st = "$($d.Status)" $ty = $(if ("$($d.InterfaceType)" -eq 'USB') { 'amovible' } elseif ("$($d.Model)" -match 'SSD') { 'ssd' } else { 'inconnu' }) [void]$liste.Add([ordered]@{ nom = "PhysicalDrive$($d.Index)"; modele = Txt $d.Model; type = $ty; bus = Txt $d.InterfaceType taille_go = [math]::Round($d.Size / 1e9); interne = $ty -ne 'amovible' smart = [ordered]@{ statut = $(if ($st -eq 'OK') { 'ok' } elseif ($st -eq 'Pred Fail') { 'defaut' } else { 'inconnu' }); source = 'Win32_DiskDrive.Status' } }) } } if (-not $Admin) { Saute $sa 'compteurs SMART (heures, usure, erreurs)' 'droits_administrateur' } $o.liste = @($liste) $S.disques = Sec $o $(if (-not $liste.Count) { 'non_disponible' } elseif ($sa.Count) { 'partiel' } else { 'releve' }) $null $sa # ---------- volumes ---------- Write-Host 'Espace disque...' $o = [ordered]@{} $o.liste = Arr (Cim Win32_LogicalDisk 'root\cimv2' 'DriveType = 3' | Where-Object { $_.Size -gt 0 } | ForEach-Object { [ordered]@{ point_montage = $_.DeviceID; systeme_fichiers = Txt $_.FileSystem; taille_go = [math]::Round($_.Size / 1GB, 1); libre_go = [math]::Round($_.FreeSpace / 1GB, 1) utilise_pct = [math]::Round(100 * ($_.Size - $_.FreeSpace) / $_.Size); inodes_utilises_pct = $null; systeme = ("$($_.DeviceID)".ToUpper() -eq $SysDrive); lecture_seule = $null } }) $S.volumes = Sec $o $(if ($o.liste.Count) { 'releve' } else { 'non_disponible' }) # ---------- batterie ---------- Write-Host 'Batterie...' $o = [ordered]@{}; $sa = New-Object System.Collections.ArrayList $b = Cim Win32_Battery $o.presente = $b.Count -gt 0 if ($b.Count) { $script:Refus = $false $sd = Cim BatteryStaticData 'root\wmi'; $fc = Cim BatteryFullChargedCapacity 'root\wmi'; $cc = Cim BatteryCycleCount 'root\wmi' if ($script:Refus) { Saute $sa "capacité d'origine et actuelle" 'droits_administrateur' } $etats = @{ 1 = 'Sur batterie'; 2 = 'Sur secteur'; 3 = 'Pleine'; 4 = 'Faible'; 5 = 'Critique'; 6 = 'En charge'; 7 = 'En charge'; 8 = 'En charge'; 9 = 'En charge'; 11 = 'Partiellement chargée' } $chem = @{ 1 = 'autre'; 3 = 'plomb'; 4 = 'Ni-Cd'; 5 = 'Ni-MH'; 6 = 'Li-ion'; 7 = 'zinc-air'; 8 = 'Li-polymère' } $bs = [int]@($b)[0].BatteryStatus $o.secteur = ($bs -eq 2 -or $bs -eq 3 -or $bs -ge 6) $l = New-Object System.Collections.ArrayList for ($i = 0; $i -lt $b.Count; $i++) { $d = $(if ($i -lt $sd.Count) { $sd[$i].DesignedCapacity } else { $null }); $f = $(if ($i -lt $fc.Count) { $fc[$i].FullChargedCapacity } else { $null }) [void]$l.Add([ordered]@{ nom = Txt $b[$i].Name; charge_pct = $b[$i].EstimatedChargeRemaining; etat = $etats[[int]$b[$i].BatteryStatus] capacite_conception_mwh = $d; capacite_pleine_mwh = $f; sante_pct = $(if ($d -and $f) { [math]::Round(100 * $f / $d) } else { $null }) cycles = $(if ($i -lt $cc.Count -and $cc[$i].CycleCount) { $cc[$i].CycleCount } else { $null }); technologie = $chem[[int]$b[$i].Chemistry] }) } $o.liste = @($l) $S.batterie = Sec $o $(if ($sa.Count) { 'partiel' } else { 'releve' }) $null $sa } else { $o.secteur = $null; $S.batterie = Sec $o 'non_disponible' } # ---------- temperatures ---------- Write-Host 'Températures...' $o = [ordered]@{}; $sa = New-Object System.Collections.ArrayList $l = New-Object System.Collections.ArrayList foreach ($z in (Cim Win32_PerfFormattedData_Counters_ThermalZoneInformation)) { $k = $(if ($z.HighPrecisionTemperature) { $z.HighPrecisionTemperature / 10 } else { $z.Temperature }) if ($k -gt 200) { [void]$l.Add([ordered]@{ nom = "Zone thermique $($z.Name)"; type = 'carte_mere'; valeur_c = [math]::Round($k - 273.15, 1) }) } } if (-not $l.Count) { $script:Refus = $false foreach ($z in (Cim MSAcpi_ThermalZoneTemperature 'root\wmi')) { if ($z.CurrentTemperature -gt 0) { [void]$l.Add([ordered]@{ nom = "Zone thermique $($z.InstanceName)"; type = 'carte_mere'; valeur_c = [math]::Round($z.CurrentTemperature / 10 - 273.15, 1); critique_c = $(if ($z.CriticalTripPoint) { [math]::Round($z.CriticalTripPoint / 10 - 273.15, 1) } else { $null }) }) } } if ($script:Refus -or -not $Admin) { Saute $sa 'zones thermiques ACPI' 'droits_administrateur' } } foreach ($pdk in $pd) { if ($Admin) { $rc = $pdk | Get-StorageReliabilityCounter -ErrorAction SilentlyContinue; if ($rc.Temperature) { [void]$l.Add([ordered]@{ nom = "Disque $($pdk.FriendlyName)"; type = 'disque'; valeur_c = $rc.Temperature; critique_c = $rc.TemperatureMax }) } } } $o.capteurs = @($l) $S.temperatures = Sec $o $(if (-not $l.Count) { 'non_disponible' } elseif ($sa.Count) { 'partiel' } else { 'releve' }) $null $sa # ---------- graphique et affichage ---------- Write-Host 'Carte graphique et écrans...' $VC = Cim Win32_VideoController $o = [ordered]@{} $o.cartes = Arr ($VC | ForEach-Object { $n = Txt $_.Name; if (-not $n) { $n = 'Carte graphique' } $ram = $_.AdapterRAM [ordered]@{ nom = $n; fabricant = Txt $_.AdapterCompatibility; pilote = Txt (@($_.InstalledDisplayDrivers -split ',')[0]); version_pilote = Txt $_.DriverVersion date_pilote = Iso $_.DriverDate; memoire_mo = $(if ($ram -gt 0) { [math]::Round($ram / 1MB) } else { $null }) en_defaut = ($_.ConfigManagerErrorCode -ne 0); code_erreur = $_.ConfigManagerErrorCode pilote_generique = ($n -match 'Basic Display|Basic Render|Standard VGA|VGA standard|affichage de base') } }) $S.graphique = Sec $o $(if ($o.cartes.Count) { 'releve' } else { 'non_disponible' }) $a = [ordered]@{ session = 'windows'; compositeur = 'Gestionnaire de fenêtres du Bureau (DWM)'; bureau = 'Explorateur Windows' } $noms = @(Cim WmiMonitorID 'root\wmi' 'Active = TRUE' | ForEach-Object { -join ($_.UserFriendlyName | Where-Object { $_ -gt 0 } | ForEach-Object { [char]$_ }) }) $bp = @(Cim WmiMonitorConnectionParams 'root\wmi' 'Active = TRUE') $ecr = New-Object System.Collections.ArrayList $k = 0 foreach ($v in $VC) { if (-not $v.CurrentHorizontalResolution) { continue } $int = $null; if ($k -lt $bp.Count) { $int = (@(-2147483648, 11, 13, 6) -contains [int]$bp[$k].VideoOutputTechnology) } [void]$ecr.Add([ordered]@{ nom = $(if ($k -lt $noms.Count) { Txt $noms[$k] } else { $null }); connecteur = $null; resolution = "$($v.CurrentHorizontalResolution)x$($v.CurrentVerticalResolution)"; frequence_hz = $v.CurrentRefreshRate; interne = $int }) $k++ } for (; $k -lt $noms.Count; $k++) { $int = $null; if ($k -lt $bp.Count) { $int = (@(-2147483648, 11, 13, 6) -contains [int]$bp[$k].VideoOutputTechnology) } [void]$ecr.Add([ordered]@{ nom = Txt $noms[$k]; connecteur = $null; resolution = $null; frequence_hz = $null; interne = $int }) } $a.ecrans = @($ecr) $S.affichage = Sec $a 'releve' # ---------- reseau ---------- Write-Host 'Réseau...' $o = [ordered]@{} $cf = Cim Win32_NetworkAdapterConfiguration 'root\cimv2' 'IPEnabled = TRUE' $ad = @{}; foreach ($x in (Cim Win32_NetworkAdapter)) { $ad[[int]$x.Index] = $x } $wifiIdx = @{}; foreach ($na in @(Get-NetAdapter -ErrorAction SilentlyContinue)) { if ("$($na.PhysicalMediaType)" -match '802\.11') { $wifiIdx["$($na.InterfaceDescription)"] = $true } } $gws = New-Object System.Collections.ArrayList; $dns = New-Object System.Collections.ArrayList; $v6 = $false $o.interfaces = Arr ($cf | ForEach-Object { $ds = "$($_.Description)"; $x = $ad[[int]$_.Index] $ty = $(if ($wifiIdx[$ds] -or $ds -match 'Wireless|Wi-Fi|WiFi|WLAN|802\.11|sans fil|Centrino|Advanced-N|Ultimate-N|Wireless-N|Wireless-AC') { 'wifi' } elseif ($ds -match 'Virtual|virtuel|VPN|TAP-|Loopback|Miniport|Hyper-V|VMware|VirtualBox|Bluetooth|Teredo|ISATAP|WireGuard|Tailscale') { 'virtuelle' } else { 'ethernet' }) $v4 = @($_.IPAddress | Where-Object { $_ -match '^\d+\.\d+\.\d+\.\d+$' }) $g6 = [bool](@($_.IPAddress | Where-Object { $_ -match ':' -and $_ -notmatch '^fe80' -and $_ -ne '::1' }).Count) if ($g6) { $script:v6 = $true } foreach ($g in @($_.DefaultIPGateway)) { if ($g -match '^\d+\.\d+\.\d+\.\d+$' -and -not $gws.Contains($g)) { [void]$gws.Add($g) } } foreach ($n in @($_.DNSServerSearchOrder)) { if ($n -and -not $dns.Contains($n)) { [void]$dns.Add($n) } } $ncs = $x.NetConnectionStatus; $sp = $x.Speed [ordered]@{ nom = $(if ($ds) { $ds } else { "Interface $($_.Index)" }); type = $ty; etat = $(if ($ncs -eq 2) { 'active' } elseif ($null -eq $ncs) { 'inconnu' } else { 'inactive' }) mac_prefixe = MacPrefixe $_.MACAddress; ipv4 = $v4; ipv6_globale = $g6; dhcp = [bool]$_.DHCPEnabled vitesse_mbps = $(if ($sp -and $sp -lt 1e12) { [math]::Round($sp / 1e6) } else { $null }) } }) $o.passerelles = @($gws); $o.dns = @($dns); $o.ipv6_active = $v6 $o.proxy = ((Reg 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' ProxyEnable) -eq 1) $S.reseau = Sec $o $(if ($cf.Count) { 'releve' } else { 'non_disponible' }) # ---------- demarrage ---------- Write-Host 'Démarrage, services et pilotes...' $o = [ordered]@{ gestionnaire = 'windows' }; $sa = New-Object System.Collections.ArrayList $bt = Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-Diagnostics-Performance/Operational'; Id = 100 } -MaxEvents 1 -ErrorAction SilentlyContinue $o.duree_s = $null if ($bt) { $x = [xml]$bt.ToXml(); $ms = ($x.Event.EventData.Data | Where-Object { $_.Name -eq 'BootTime' }).'#text'; if ($ms) { $o.duree_s = [math]::Round([double]$ms / 1000, 1) } } else { Saute $sa 'durée du démarrage (journal Diagnostics-Performance)' 'droits_administrateur' } $o.services_echec = Arr (Cim Win32_Service 'root\cimv2' "StartMode = 'Auto' AND State = 'Stopped'" | Where-Object { $_.ExitCode -ne 0 -and $_.ExitCode -ne 1077 } | ForEach-Object { [ordered]@{ nom = $_.Name; detail = "code de sortie $($_.ExitCode)"; systeme = $true } }) $o.pilotes_defaut = Arr (Cim Win32_PnPEntity 'root\cimv2' 'ConfigManagerErrorCode <> 0' | ForEach-Object { $n = Txt $_.Name; if (-not $n) { $n = 'Périphérique inconnu ' + (DevId $_.DeviceID) } [ordered]@{ nom = $n; code = $_.ConfigManagerErrorCode; classe = $(if ($_.PNPClass) { $_.PNPClass } else { DevId $_.DeviceID }) } }) $Reboot = (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired') -or (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending') $o.redemarrage_requis = $Reboot $Depuis30 = (Get-Date).AddDays(-30) $ev30 = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 41, 6008, 1001; StartTime = $Depuis30 } -ErrorAction SilentlyContinue) $o.arrets_inattendus_30j = @($ev30 | Where-Object { $_.Id -eq 41 -or $_.Id -eq 6008 }).Count $o.plantages_noyau_30j = @($ev30 | Where-Object { $_.Id -eq 1001 -and $_.ProviderName -match 'BugCheck|WER-SystemErrorReporting' }).Count $S.demarrage = Sec $o $(if ($sa.Count) { 'partiel' } else { 'releve' }) $null $sa # ---------- journaux ---------- Write-Host "Journaux d'erreurs (7 jours)..." $o = [ordered]@{ periode_h = 168; source = 'journaux Système et Application' }; $sa = New-Object System.Collections.ArrayList $sig = @( @('disque_es', '^(disk|atapi|iastor.*|storahci|stornvme|nvme|volmgr|amdsata)$', @(7, 9, 11, 15, 51, 153, 129, 161)), @('systeme_fichiers', '^ntfs$', @(55, 98, 137, 140)), @('memoire_saturee', 'resource-exhaustion-detector', @(2004)), @('erreur_materielle', 'whea-logger', $null), @('graphique_blocage', '^display$', @(4101)), @('thermique', 'kernel-power', @(86, 125)), @('plantage_appli', '^(application error|application hang|\.net runtime|windows error reporting)$', @(1000, 1002, 1026, 1001)), @('arret_inattendu', '^(eventlog|microsoft-windows-kernel-power|microsoft-windows-wer-systemerrorreporting)$', @(6008, 41, 1001)), @('usb', '^(usbhub|usbhub3|usbxhci|usbport)$', $null), @('reseau', '^(tcpip|dhcp|microsoft-windows-dhcp-client|netbt|e1express|e1cexpress|rt640x64|netwtw.*)$', $null), @('pilote', '^service control manager$', @(7000, 7009, 7011, 7026, 7034, 7031)) ) $Depuis7 = (Get-Date).AddDays(-7) $err = @(Get-WinEvent -FilterHashtable @{ LogName = 'System', 'Application'; Level = 1, 2; StartTime = $Depuis7 } -MaxEvents 20000 -ErrorAction SilentlyContinue) $avert = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 3; StartTime = $Depuis7; ProviderName = 'Microsoft-Windows-WHEA-Logger', 'Microsoft-Windows-Kernel-Power', 'disk', 'Ntfs', 'stornvme', 'storahci' } -MaxEvents 5000 -ErrorAction SilentlyContinue) $ev = @($err) + @($avert) $cnt = [ordered]@{}; foreach ($s in $sig) { $cnt[$s[0]] = 0 } foreach ($e in $ev) { $src = "$($e.ProviderName)".ToLower() -replace '^microsoft-windows-', '' $full = "$($e.ProviderName)".ToLower() foreach ($s in $sig) { if (($src -match $s[1] -or $full -match $s[1]) -and ($null -eq $s[2] -or $s[2] -contains $e.Id)) { if ($e.Level -le 2 -or $s[0] -eq 'thermique' -or $s[0] -eq 'erreur_materielle' -or $s[0] -eq 'disque_es') { $cnt[$s[0]]++ } } } } $o.total_erreurs = $err.Count $o.signatures = $cnt $o.groupes = Arr ($err | Group-Object ProviderName, Id | Sort-Object Count -Descending | Select-Object -First 20 | ForEach-Object { $f = $_.Group[0] [ordered]@{ source = "$($f.ProviderName)"; code = "$($f.Id)"; nombre = $_.Count; dernier = Iso ((@($_.Group | Sort-Object TimeCreated -Descending))[0].TimeCreated) } }) if (-not $Admin) { Saute $sa 'journal Sécurité' 'droits_administrateur' } $S.journaux = Sec $o 'releve' $null $sa # ---------- mises_a_jour ---------- Write-Host 'Mises à jour en attente (cache local, sans réseau)...' $o = [ordered]@{ gestionnaire = 'Windows Update' }; $sa = New-Object System.Collections.ArrayList try { $se = New-Object -ComObject Microsoft.Update.Session; $sr = $se.CreateUpdateSearcher(); $sr.Online = $false $res = $sr.Search("IsInstalled=0 and IsHidden=0 and Type='Software'") $o.en_attente = $res.Updates.Count $nsec = 0 foreach ($u in $res.Updates) { if ($u.MsrcSeverity -or @($u.Categories | Where-Object { $_.CategoryID -eq '0fa1201d-4330-4fa8-8ae9-b877473b6441' }).Count) { $nsec++ } } $o.securite_en_attente = $nsec } catch { $o.en_attente = $null; $o.securite_en_attente = $null; Saute $sa 'liste des mises à jour en attente' 'erreur' } try { $au = New-Object -ComObject Microsoft.Update.AutoUpdate $o.derniere_installation = Iso $au.Results.LastInstallationSuccessDate $o.derniere_recherche = Iso $au.Results.LastSearchSuccessDate } catch { $o.derniere_installation = $null; $o.derniere_recherche = $null } $hf = Get-HotFix -ErrorAction SilentlyContinue | Where-Object { $_.InstalledOn } | Sort-Object InstalledOn -Descending | Select-Object -First 1 if ($hf -and -not $o.derniere_installation) { $o.derniere_installation = Iso $hf.InstalledOn } $pol = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU' $o.automatiques = -not ((Reg $pol NoAutoUpdate) -eq 1) $o.redemarrage_requis = $Reboot $o.source_hors_ligne = $true $S.mises_a_jour = Sec $o $(if ($sa.Count) { 'partiel' } else { 'releve' }) 'dernière recherche enregistrée par Windows Update' $sa # ---------- securite ---------- Write-Host 'Sécurité...' $o = [ordered]@{}; $sa = New-Object System.Collections.ArrayList $fw = $null; $fwp = 'Pare-feu Windows Defender' $prof = @(Get-NetFirewallProfile -ErrorAction SilentlyContinue) if ($prof.Count) { $fw = [bool](@($prof | Where-Object { $_.Enabled -eq $true -or "$($_.Enabled)" -eq 'True' }).Count) } else { try { $p2 = New-Object -ComObject HNetCfg.FwPolicy2; $cur = $p2.CurrentProfileTypes; $fw = $false; foreach ($bit in 1, 2, 4) { if (($cur -band $bit) -and $p2.FirewallEnabled($bit)) { $fw = $true } } } catch { } } foreach ($fp in (Cim FirewallProduct 'root\SecurityCenter2')) { if ((([int]$fp.productState -shr 12) -band 0xF) -eq 1) { $fw = $true; $fwp = Txt $fp.displayName } } $o.pare_feu_actif = $fw; $o.pare_feu_produit = $fwp $avl = New-Object System.Collections.ArrayList foreach ($av in (Cim AntiVirusProduct 'root\SecurityCenter2')) { $ps = [int]$av.productState [void]$avl.Add([ordered]@{ nom = $(if ($av.displayName) { "$($av.displayName)" } else { 'Antivirus' }); actif = ((($ps -shr 12) -band 0xF) -eq 1); a_jour = ((($ps -shr 4) -band 0xF) -eq 0) }) } if (-not $avl.Count) { $mp = Get-MpComputerStatus -ErrorAction SilentlyContinue if ($mp) { [void]$avl.Add([ordered]@{ nom = 'Microsoft Defender'; actif = [bool]$mp.RealTimeProtectionEnabled; a_jour = ($mp.AntivirusSignatureAge -le 7) }) } } $o.antivirus = @($avl) $o.chiffrement_actif = $null; $o.chiffrement_methode = $null try { $bl = (New-Object -ComObject Shell.Application).NameSpace("$SysDrive\").Self.ExtendedProperty('System.Volume.BitLockerProtection') if (@(1, 3, 5, 6) -contains $bl) { $o.chiffrement_actif = $true; $o.chiffrement_methode = 'BitLocker' } elseif ($bl -eq 2) { $o.chiffrement_actif = $false } } catch { } if ($null -eq $o.chiffrement_actif) { $blv = Get-BitLockerVolume -MountPoint $SysDrive -ErrorAction SilentlyContinue if ($blv) { $o.chiffrement_actif = ("$($blv.ProtectionStatus)" -eq 'On'); if ($o.chiffrement_actif) { $o.chiffrement_methode = 'BitLocker' } } else { Saute $sa 'état de BitLocker' 'droits_administrateur' } } $sb = Reg 'HKLM:\SYSTEM\CurrentControlSet\Control\SecureBoot\State' UEFISecureBootEnabled $o.demarrage_securise = $(if ($null -ne $sb) { $sb -eq 1 } elseif ($S.machine.micrologiciel_type -eq 'bios') { $false } else { $null }) $o.protection_integrite = $null $ss = Reg 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer' SmartScreenEnabled $ssp = Reg 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\System' EnableSmartScreen $o.controle_applications = $(if ($null -ne $ssp) { $ssp -eq 1 } elseif ($ss) { $ss -ne 'Off' } else { $null }) $lua = Reg 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' EnableLUA $o.module_securite = $(if ($lua -eq 0) { "Contrôle de compte d'utilisateur désactivé" } else { "Contrôle de compte d'utilisateur actif" }) $S.securite = Sec $o $(if ($sa.Count) { 'partiel' } else { 'releve' }) $null $sa # ---------- logiciels_demarrage ---------- Write-Host 'Logiciels au démarrage...' $o = [ordered]@{} $el = @(Cim Win32_StartupCommand | ForEach-Object { $ll = "$($_.Location)".ToLower() [ordered]@{ nom = $(if ($_.Name) { "$($_.Name)" } else { '?' }); portee = $(if ($ll -match '^hklm|common startup' -or $ll -match '^hku\\s-1-5-(18|19|20)\\') { 'systeme' } else { 'utilisateur' }); mecanisme = $(if ($ll -match '^hk') { 'Run' } else { 'Startup' }) } }) $o.nombre = $el.Count $o.elements = Arr ($el | Select-Object -First 60) $S.logiciels_demarrage = Sec $o 'releve' # ---------- bilan_securite (#2599, #2612, format 1.1) : signes relevés, lecture seule ---------- # Seules requêtes réseau, bornées : une poignée TLS vers store.apinetwork.fr, une connexion TCP fermée aussitôt par port de la box. Write-Host 'Bilan de sécurité...' $B = [ordered]@{} function Nd { [ordered]@{ statut = 'non_disponible' } } function Liste($l) { $a = @($l | Where-Object { $_ }); [ordered]@{ statut = 'releve'; nombre = $a.Count; elements = Arr ($a | Select-Object -First 40 | ForEach-Object { if ($_ -is [string]) { [ordered]@{ nom = $_ } } else { $_ } }) } } function Val($v) { [ordered]@{ statut = 'releve'; valeur = $v } } function Cmd($n) { [bool](Get-Command $n -ErrorAction SilentlyContinue) } $mp = $null; if (Cmd Get-MpComputerStatus) { $mp = Get-MpComputerStatus -ErrorAction SilentlyContinue } if ($mp) { $ages = @($mp.QuickScanAge, $mp.FullScanAge | Where-Object { $null -ne $_ -and $_ -lt 100000 }) $B.defender_analyse_jours = $(if ($ages.Count) { Val ([int]($ages | Measure-Object -Minimum).Minimum) } else { Val 9999 }) $B.defender_menaces = Liste @(Get-MpThreat -ErrorAction SilentlyContinue | Where-Object { $_.IsActive } | ForEach-Object { "$($_.ThreatName)" }) } else { $B.defender_analyse_jours = Nd; $B.defender_menaces = Nd } $ns = New-Object System.Collections.ArrayList if (Cmd Get-AuthenticodeSignature) { foreach ($sc in (Cim Win32_StartupCommand)) { $c = [Environment]::ExpandEnvironmentVariables("$($sc.Command)") $f = $(if ($c -match '^"([^"]+)"') { $Matches[1] } elseif ($c -match '^(.+?\.exe)\b') { $Matches[1] } else { $null }) if ($f -and (Test-Path -LiteralPath $f)) { if ((Get-AuthenticodeSignature -LiteralPath $f -ErrorAction SilentlyContinue).Status -ne 'Valid') { [void]$ns.Add("$($sc.Name)") } } } $B.demarrage_non_signes = Liste $ns } else { $B.demarrage_non_signes = Nd } if (Cmd Get-ScheduledTask) { $B.taches_hors_microsoft = Liste @(Get-ScheduledTask -ErrorAction SilentlyContinue | Where-Object { $_.TaskPath -notlike '\Microsoft\*' -and "$($_.State)" -ne 'Disabled' } | ForEach-Object { "$($_.TaskName)" }) } else { $B.taches_hors_microsoft = Nd } $sr = "$env:SystemRoot".ToLower() $B.services_hors_microsoft = Liste @(Cim Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.PathName -and "$($_.PathName)".Trim('"').ToLower() -notlike "$sr*" -and "$($_.PathName)".ToLower() -notlike '\systemroot\*' } | ForEach-Object { "$($_.Name)" }) $ext = New-Object System.Collections.ArrayList foreach ($nav in @(@('Chrome', "$env:LOCALAPPDATA\Google\Chrome\User Data"), @('Edge', "$env:LOCALAPPDATA\Microsoft\Edge\User Data"))) { foreach ($d in @(Get-ChildItem -Path "$($nav[1])\*\Extensions\*" -Directory -ErrorAction SilentlyContinue)) { if ($d.Name -match '^[a-p]{32}$') { [void]$ext.Add([ordered]@{ nom = $d.Name; detail = $nav[0] }) } } } foreach ($x in @(Get-ChildItem -Path "$env:APPDATA\Mozilla\Firefox\Profiles\*\extensions\*.xpi" -ErrorAction SilentlyContinue)) { [void]$ext.Add([ordered]@{ nom = $x.BaseName; detail = 'Firefox' }) } $B.extensions_navigateur = Liste ($ext | Sort-Object { $_.nom } -Unique) $iss = $null try { $tc = New-Object Net.Sockets.TcpClient; $ar = $tc.BeginConnect('store.apinetwork.fr', 443, $null, $null) if ($ar.AsyncWaitHandle.WaitOne(5000)) { $tc.EndConnect($ar); $ss = New-Object Net.Security.SslStream($tc.GetStream(), $false, ({ $true } -as [Net.Security.RemoteCertificateValidationCallback])); $ss.ReadTimeout = 5000; $ss.AuthenticateAsClient('store.apinetwork.fr'); if ("$($ss.RemoteCertificate.Issuer)" -match 'O=("[^"]+"|[^,]+)') { $iss = $Matches[1].Trim('"') }; $ss.Close() } $tc.Close() } catch { } $B.https_intercepte = $(if ($iss) { Val $iss } else { Nd }) $B.dns_chiffre = $(if (Cmd Get-DnsClientDohServerAddress) { Val ([bool]@(Get-DnsClientDohServerAddress -ErrorAction SilentlyContinue).Count) } else { Nd }) $gw = $null; $mtu = $null if (Cmd Get-NetRoute) { $rt = @(Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue | Sort-Object RouteMetric) | Select-Object -First 1 if ($rt) { $gw = "$($rt.NextHop)"; $mtu = (Get-NetIPInterface -InterfaceIndex $rt.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue).NlMtu } $B.ipv6 = Val ([bool]@(Get-NetIPAddress -AddressFamily IPv6 -ErrorAction SilentlyContinue | Where-Object { "$($_.IPAddress)" -match '^[23]' }).Count) } else { $B.ipv6 = Nd } if (-not $gw) { $gw = @(Cim Win32_NetworkAdapterConfiguration 'root\cimv2' 'IPEnabled = TRUE' | ForEach-Object { $_.DefaultIPGateway } | Where-Object { "$_" -match '^\d+\.' }) | Select-Object -First 1 } $B.mtu = $(if ($mtu) { Val ([int]$mtu) } else { Nd }) $B.nat = $(if (-not $gw) { Nd } elseif ("$gw" -match '^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)') { Val 'rfc1918' } elseif ("$gw" -match '^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.') { Val 'cgnat' } else { Val 'aucun' }) $wl = @(netsh wlan show interfaces 2>$null | Where-Object { $_ -match '^\s*Auth\w*\s*:\s*(.+)$' } | ForEach-Object { $Matches[1].Trim() }) | Select-Object -First 1 $B.wifi_chiffrement = $(if ($wl) { Val "$wl" } else { Nd }) if ($gw) { $ou = New-Object System.Collections.ArrayList foreach ($pt in 21, 23, 80, 443, 8080, 7547) { try { $c = New-Object Net.Sockets.TcpClient; $a = $c.BeginConnect("$gw", $pt, $null, $null); if ($a.AsyncWaitHandle.WaitOne(2000) -and $c.Connected) { [void]$ou.Add("$pt") }; $c.Close() } catch { } } $B.passerelle_ports = Liste $ou } else { $B.passerelle_ports = Nd } try { $up = (New-Object -ComObject HNetCfg.NATUPnP).StaticPortMappingCollection; $B.upnp = Val ($null -ne $up) } catch { $B.upnp = Nd } $B.partages = Liste @(Cim Win32_Share | Where-Object { $_.Type -eq 0 -and "$($_.Name)" -notmatch '\$$' } | ForEach-Object { [ordered]@{ nom = "$($_.Name)"; detail = 'smb' } }) $S.bilan_securite = [ordered]@{ statut = 'releve'; sondes = $B } # ---------- écriture ---------- $R = [ordered]@{ format = 'apinetwork-diagnostic'; version_format = '1.1.0' collecteur = [ordered]@{ nom = 'windows-ps'; version = $VersionCollecteur; interprete = "PowerShell $($PSVersionTable.PSVersion)"; administrateur = $Admin; duree_s = [int]((Get-Date) - $T0).TotalSeconds } genere_le = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ'); famille = 'windows' anonymise = [ordered]@{ utilisateur = ''; machine = ''; mac = 'prefixe-constructeur' } sections = $S } $json = $R | ConvertTo-Json -Depth 10 -Compress foreach ($n in @($env:COMPUTERNAME, $env:USERNAME)) { if ($n -and $n.Length -ge 3 -and $n -notmatch '^(administrator|administrateur|admin|user|guest|test|windows|localhost|pc|desktop)$') { $rep = $(if ($n -eq $env:COMPUTERNAME) { '' } else { '' }) $json = [regex]::Replace($json, '(?