🟣 C# / .NET 6+

Backup Operating System Info to JSON (C#)

Snapshots Operating System Info (Win32_OperatingSystem) to a timestamped JSON file via System.Management and System.Text.Json.

By WindowsScripting.com · 1.3 KB
BackupOperatingSystemListToJson.cs
// BackupOperatingSystemListToJson.cs
//
// Snapshots Operating System Info (Win32_OperatingSystem) to a timestamped JSON file.
//
// Requires the System.Management package:
//   dotnet new console -o BackupOperatingSystem
//   dotnet add package System.Management
//   (replace the generated Program.cs with this file, then dotnet run)

using System;
using System.Collections.Generic;
using System.IO;
using System.Management;
using System.Text.Json;

var searcher = new ManagementObjectSearcher("SELECT Caption, Version, OSArchitecture, LastBootUpTime, FreePhysicalMemory FROM Win32_OperatingSystem");
var results = new List<Dictionary<string, object?>>();

foreach (ManagementObject item in searcher.Get())
{
    var row = new Dictionary<string, object?>();
    row["Caption"] = item["Caption"];
        row["Version"] = item["Version"];
        row["OSArchitecture"] = item["OSArchitecture"];
        row["LastBootUpTime"] = item["LastBootUpTime"];
        row["FreePhysicalMemory"] = item["FreePhysicalMemory"];
    results.Add(row);
}

string timestamp = DateTime.Now.ToString("yyyyMMdd-HHmmss");
string outPath = $"operatingsystem-snapshot_{timestamp}.json";
File.WriteAllText(outPath, JsonSerializer.Serialize(results, new JsonSerializerOptions { WriteIndented = true }));

Console.WriteLine($"Snapshot of Operating System Info ({results.Count} items) saved to {outPath}");