"use strict"; // Windows system metrics for chj.system-monitor (Windows 11, Windows Server incl. Server Core). // Runs one fixed PowerShell script per refresh through the existing SSH session. .NET and the registry // are the primary sources (they also work for standard accounts, which are often denied WMI/CIM over SSH); // CIM performance classes add details when permitted. Values Windows does not provide are null, never 0. const METRICS_SCRIPT = String.raw`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) } 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 } } $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)))) `; const finite = (value) => { if (value === null || value === undefined || value === "") return null; const number = Number(value); return Number.isFinite(number) ? number : null; }; const text = (value, limit = 240) => String(value ?? "").replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, limit); function cpuUsage(previous, current) { if (!previous || !current) return null; const busy = Number(BigInt(current.busyInverse) - BigInt(previous.busyInverse)); const time = Number(BigInt(current.time) - BigInt(previous.time)); if (!(time > 0)) return null; // PERF_100NSEC_TIMER_INV: the counter measures idle time; usage = 1 - delta(idle) / delta(time). return Math.max(0, Math.min(100, (1 - busy / time) * 100)); } function rate(previous, current, key) { if (!previous || !current || !current.frequency) return null; const count = Number(BigInt(current[key]) - BigInt(previous[key])); const seconds = Number(BigInt(current.time) - BigInt(previous.time)) / Number(current.frequency); return seconds > 0 && count >= 0 ? count / seconds : null; } // Normalizes the script output into the shared metrics structure. state keeps the previous raw samples. function normalizeWindowsMetrics(raw, staticInfo, state = {}, fallbackHostname = "unknown") { const s = staticInfo || {}; const total = finite(raw.memoryTotal) ?? finite(s.memoryTotal); const available = finite(raw.memoryAvailable); const counters = raw.memoryCounters || null; const usage = cpuUsage(state.cpuRaw, raw.cpuRaw); const pagefiles = Array.isArray(raw.pagefiles) ? raw.pagefiles.map((file) => ({ name: text(file.name, 260), allocated: finite(file.allocatedMb) === null ? null : file.allocatedMb * 1048576, used: finite(file.currentMb) === null ? null : file.currentMb * 1048576, peak: finite(file.peakMb) === null ? null : file.peakMb * 1048576, temporary: file.temporary === true })) : null; const pageTotal = pagefiles ? pagefiles.reduce((sum, file) => sum + (file.allocated || 0), 0) : null; const pageUsed = pagefiles ? pagefiles.reduce((sum, file) => sum + (file.used || 0), 0) : null; const disks = (raw.disks || []).map((disk) => ({ name: text(disk.name, 16), total: finite(disk.total), available: finite(disk.available), used: finite(disk.total) !== null && finite(disk.free) !== null ? disk.total - disk.free : null, format: text(disk.format, 16), label: text(disk.label, 64) })); const systemDrive = disks.find((disk) => disk.name.toLowerCase() === String(raw.systemDrive || "C:").toLowerCase()) || disks[0] || null; const adapters = (raw.adapters || []).slice(0, 64); const defaultAdapter = adapters.find((adapter) => adapter.gateway && adapter.state === "Up"); let memoryDetail = null; if (counters && total) { const standby = (counters.standbyCore || 0) + (counters.standbyNormal || 0) + (counters.standbyReserve || 0); const inUse = Math.max(0, total - counters.available - counters.modified); memoryDetail = { source: "Win32_PerfRawData_PerfOS_Memory", // Non-overlapping physical pages: in use + modified + standby + free/zero ~= total. slices: { inUse, modified: counters.modified, standby, free: counters.freeZero }, available: counters.available, systemCache: counters.systemCacheResident, cacheBytes: counters.cache, kernel: { pagedPool: counters.poolPaged, nonpagedPool: counters.poolNonpaged, systemCode: counters.systemCode, systemDriver: counters.systemDriver }, commit: { committed: counters.committed, limit: counters.commitLimit }, paging: { pagesInPerSecond: rate(state.memoryCounters, counters, "pagesInput"), pagesOutPerSecond: rate(state.memoryCounters, counters, "pagesOutput") } }; } return { os: "windows", platform: "Windows", kernel: [s.build ? `build ${s.build}${s.ubr ? `.${s.ubr}` : ""}` : "", text(s.displayVersion, 20)].filter(Boolean).join(" ") || null, osName: text(s.caption, 120) || null, installationType: text(s.installationType, 40) || null, hostname: text(s.hostname, 120) || fallbackHostname, uptimeSeconds: finite(raw.uptimeSeconds), load1: null, loadAverageSupported: false, processorQueueLength: finite(raw.processorQueueLength), processes: finite(raw.processes), memory: { total, available }, memoryDetail, swap: { kind: "pagefile", total: pageTotal, used: pageUsed, free: pageTotal !== null && pageUsed !== null ? Math.max(0, pageTotal - pageUsed) : null }, pagefiles, disk: systemDrive ? { mount: systemDrive.name, total: systemDrive.total, used: systemDrive.used, available: systemDrive.available } : { mount: null, total: null, used: null, available: null }, disks, cpu: { usagePercent: usage, usagePending: usage === null && Boolean(raw.cpuRaw), architecture: text(s.architecture, 32) || null, model: text(s.cpuModel, 160) || null, logicalCores: finite(s.logical), physicalCores: finite(s.physical), sockets: finite(s.sockets), coreTypes: [] }, network: { defaultInterface: defaultAdapter ? text(defaultAdapter.name, 64) : "", interfaces: adapters.map((adapter) => { // Some virtual NIC drivers (e.g. emulated Intel PRO/1000) report 0 octets while packets flow. const bytesReported = !(finite(adapter.rx) === 0 && finite(adapter.tx) === 0 && (finite(adapter.rxPackets) > 0 || finite(adapter.txPackets) > 0)); return { name: text(adapter.name, 64), description: text(adapter.description, 120), state: adapter.state === "Up" ? "up" : text(adapter.state, 24).toLowerCase(), mac: text(adapter.mac, 64), rxBytes: bytesReported ? finite(adapter.rx) : null, txBytes: bytesReported ? finite(adapter.tx) : null, rxPackets: finite(adapter.rxPackets), txPackets: finite(adapter.txPackets), bytesUnavailableReason: bytesReported ? null : "The network driver does not report transferred bytes (packets are counted).", speedBitsPerSecond: finite(adapter.speed) > 0 ? adapter.speed : null, addresses: (adapter.addresses || []).slice(0, 16).map((address) => text(address, 64)), isDefault: adapter === defaultAdapter }; }) }, unavailable: (raw.errors || []).slice(0, 10).map((entry) => text(entry, 200)) }; } module.exports = { METRICS_SCRIPT, cpuUsage, normalizeWindowsMetrics };