param([string]$ArgsJson) $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue' $A = $ArgsJson | ConvertFrom-Json $out = [ordered]@{ errors = @() } function Try-Cim([string]$Class, [string]$Filter) { try { if ($Filter) { return @(Get-CimInstance -ClassName $Class -Filter $Filter -ErrorAction Stop) } else { return @(Get-CimInstance -ClassName $Class -ErrorAction Stop) } } catch { $script:out.errors += "$($Class): $($_.Exception.Message)"; return $null } } if ($A.static) { $nt = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction SilentlyContinue $cpuKey = Get-ItemProperty 'HKLM:\HARDWARE\DESCRIPTION\System\CentralProcessor\0' -ErrorAction SilentlyContinue $static = [ordered]@{ caption = [string]$nt.ProductName; build = [string]$nt.CurrentBuildNumber; ubr = [string]$nt.UBR; displayVersion = [string]$nt.DisplayVersion installationType = [string]$nt.InstallationType; hostname = [Environment]::MachineName; architecture = [string]$env:PROCESSOR_ARCHITECTURE cpuModel = ([string]$cpuKey.ProcessorNameString).Trim(); logical = [Environment]::ProcessorCount; physical = $null; sockets = $null; memoryTotal = $null } $os = Try-Cim 'Win32_OperatingSystem' if ($os) { $static.caption = [string]$os[0].Caption; $static.memoryTotal = [double]$os[0].TotalVisibleMemorySize * 1024 } $cpu = Try-Cim 'Win32_Processor' if ($cpu) { $static.sockets = $cpu.Count; $static.physical = [int](($cpu | Measure-Object -Property NumberOfCores -Sum).Sum); $static.logical = [int](($cpu | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum) } $video = Try-Cim 'Win32_VideoController' if ($video) { $static.gpus = @($video | ForEach-Object { [ordered]@{ name = [string]$_.Name; vendor = [string]$_.AdapterCompatibility; driverVersion = [string]$_.DriverVersion; pnp = [string]$_.PNPDeviceID; adapterRam = $(if ($null -ne $_.AdapterRAM) { [double]$_.AdapterRAM } else { $null }) } }) } if (-not $static.memoryTotal) { try { Add-Type -AssemblyName Microsoft.VisualBasic; $static.memoryTotal = [double](New-Object Microsoft.VisualBasic.Devices.ComputerInfo).TotalPhysicalMemory } catch { $out.errors += "ComputerInfo: $($_.Exception.Message)" } } $out.static = $static } # Uptime: CIM boot time, otherwise the monotonic performance counter since boot. $out.uptimeSeconds = $null $os = Try-Cim 'Win32_OperatingSystem' if ($os) { $out.uptimeSeconds = [math]::Floor(((Get-Date) - $os[0].LastBootUpTime).TotalSeconds) $out.memoryTotal = [double]$os[0].TotalVisibleMemorySize * 1024; $out.memoryAvailable = [double]$os[0].FreePhysicalMemory * 1024 } else { $out.uptimeSeconds = [math]::Floor([Diagnostics.Stopwatch]::GetTimestamp() / [Diagnostics.Stopwatch]::Frequency) try { Add-Type -AssemblyName Microsoft.VisualBasic; $ci = New-Object Microsoft.VisualBasic.Devices.ComputerInfo; $out.memoryTotal = [double]$ci.TotalPhysicalMemory; $out.memoryAvailable = [double]$ci.AvailablePhysicalMemory } catch { $out.errors += "ComputerInfo: $($_.Exception.Message)" } } # Raw CPU counter; Core computes the usage from the difference between two refreshes. $cpu = Try-Cim 'Win32_PerfRawData_PerfOS_Processor' "Name='_Total'" if ($cpu) { $out.cpuRaw = [ordered]@{ busyInverse = [string]$cpu[0].PercentProcessorTime; time = [string]$cpu[0].Timestamp_Sys100NS } } # Each CPU package separately. $packages = Try-Cim 'Win32_Processor' if ($packages) { $out.cpuPackages = @($packages | ForEach-Object { [ordered]@{ id = [string]$_.DeviceID; name = ([string]$_.Name).Trim(); cores = [int]$_.NumberOfCores; logical = [int]$_.NumberOfLogicalProcessors; load = $(if ($null -ne $_.LoadPercentage) { [double]$_.LoadPercentage } else { $null }); mhz = [double]$_.CurrentClockSpeed } }) } # GPU metrics: nvidia-smi where installed, Windows GPU performance counters otherwise (absent on systems without WDDM counters). $smi = $null try { $smi = (Get-Command 'nvidia-smi.exe' -ErrorAction Stop).Source } catch { $candidate = Join-Path ([string]$env:ProgramFiles) 'NVIDIA Corporation\NVSMI\nvidia-smi.exe'; if (Test-Path -LiteralPath $candidate) { $smi = $candidate } } if ($smi) { try { $ErrorActionPreference = 'Continue' $out.nvidia = @(& $smi '--query-gpu=pci.bus_id,name,utilization.gpu,utilization.memory,memory.total,memory.used,temperature.gpu,power.draw,power.limit,clocks.current.graphics,fan.speed,driver_version' '--format=csv,noheader,nounits' 2>$null | ForEach-Object { [string]$_ }) } catch {} finally { $ErrorActionPreference = 'Stop' } } $engines = $null; $adapterMemory = $null try { $engines = @(Get-CimInstance -ClassName Win32_PerfFormattedData_GPUPerformanceCounters_GPUEngine -ErrorAction Stop); $adapterMemory = @(Get-CimInstance -ClassName Win32_PerfFormattedData_GPUPerformanceCounters_GPUAdapterMemory -ErrorAction Stop) } catch {} if ($adapterMemory) { $busy = @{} foreach ($engine in $engines) { if ($engine.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+).*engtype_(.*)$') { $key = "$($Matches[1])|$($Matches[2])"; $busy[$key] = [double]$busy[$key] + [double]$engine.UtilizationPercentage } } $out.gpuCounters = @($adapterMemory | ForEach-Object { $luid = if ($_.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)') { $Matches[1] } else { [string]$_.Name } $peak = $null; foreach ($key in $busy.Keys) { if ($key.StartsWith("$luid|") -and ($null -eq $peak -or $busy[$key] -gt $peak)) { $peak = $busy[$key] } } [ordered]@{ luid = $luid; usage = $peak; dedicated = [double]$_.DedicatedUsage; shared = [double]$_.SharedUsage } }) } $system = Try-Cim 'Win32_PerfRawData_PerfOS_System' if ($system) { $out.processorQueueLength = [int]$system[0].ProcessorQueueLength; $out.processes = [int]$system[0].Processes } # Physical memory lists (gauges, no second sample needed). $memory = Try-Cim 'Win32_PerfRawData_PerfOS_Memory' if ($memory) { $m = $memory[0] $out.memoryCounters = [ordered]@{ available = [double]$m.AvailableBytes; cache = [double]$m.CacheBytes; systemCacheResident = [double]$m.SystemCacheResidentBytes standbyCore = [double]$m.StandbyCacheCoreBytes; standbyNormal = [double]$m.StandbyCacheNormalPriorityBytes; standbyReserve = [double]$m.StandbyCacheReserveBytes modified = [double]$m.ModifiedPageListBytes; freeZero = [double]$m.FreeAndZeroPageListBytes; committed = [double]$m.CommittedBytes; commitLimit = [double]$m.CommitLimit poolPaged = [double]$m.PoolPagedResidentBytes; poolNonpaged = [double]$m.PoolNonpagedBytes; systemCode = [double]$m.SystemCodeResidentBytes; systemDriver = [double]$m.SystemDriverResidentBytes pagesInput = [string]$m.PagesInputPersec; pagesOutput = [string]$m.PagesOutputPersec; time = [string]$m.Timestamp_Sys100NS; frequency = [string]$m.Frequency_Sys100NS } } # Pagefiles: allocated size, current and peak usage (MB as reported by Windows). $usage = Try-Cim 'Win32_PageFileUsage' if ($null -ne $usage) { $out.pagefiles = @($usage | ForEach-Object { [ordered]@{ name = [string]$_.Name; allocatedMb = [double]$_.AllocatedBaseSize; currentMb = [double]$_.CurrentUsage; peakMb = [double]$_.PeakUsage; temporary = [bool]$_.TempPageFile } }) } # Fixed disks through .NET (no WMI rights required). $out.disks = @([IO.DriveInfo]::GetDrives() | Where-Object { $_.DriveType -eq 'Fixed' -and $_.IsReady } | ForEach-Object { [ordered]@{ name = $_.Name.TrimEnd('\'); total = [double]$_.TotalSize; available = [double]$_.AvailableFreeSpace; free = [double]$_.TotalFreeSpace; format = [string]$_.DriveFormat; label = [string]$_.VolumeLabel } }) $out.systemDrive = [string]$env:SystemDrive # Network adapters through .NET: status, MAC, unicast addresses and cumulative byte counters. $adapters = @() foreach ($nic in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) { if ($nic.NetworkInterfaceType -in @('Loopback', 'Tunnel')) { continue } $props = $nic.GetIPProperties() $stats = $null; try { $stats = $nic.GetIPStatistics() } catch {} $addresses = @($props.UnicastAddresses | Where-Object { -not $_.Address.IsIPv6LinkLocal } | ForEach-Object { "$($_.Address.IPAddressToString)/$($_.PrefixLength)" }) $mac = ($nic.GetPhysicalAddress().GetAddressBytes() | ForEach-Object { $_.ToString('x2') }) -join ':' $adapters += [ordered]@{ name = $nic.Name; description = $nic.Description; state = [string]$nic.OperationalStatus; mac = $mac; speed = [double]$nic.Speed rx = $(if ($stats) { [double]$stats.BytesReceived } else { $null }); tx = $(if ($stats) { [double]$stats.BytesSent } else { $null }) rxPackets = $(if ($stats) { [double]$stats.UnicastPacketsReceived + [double]$stats.NonUnicastPacketsReceived } else { $null }) txPackets = $(if ($stats) { [double]$stats.UnicastPacketsSent + [double]$stats.NonUnicastPacketsSent } else { $null }) addresses = $addresses; gateway = [bool](@($props.GatewayAddresses | Where-Object { $_.Address.ToString() -notin @('0.0.0.0', '::') }).Count) } } $out.adapters = $adapters [Console]::Out.WriteLine('CHJ_RESULT:' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $out -Depth 6 -Compress))))