🟣 C# / .NET 6+
Backup Environment Variables to JSON (C#)
Snapshots Environment Variables (Win32_Environment) to a timestamped JSON file via System.Management and System.Text.Json.
BackupEnvironmentListToJson.cs
// BackupEnvironmentListToJson.cs
//
// Snapshots Environment Variables (Win32_Environment) to a timestamped JSON file.
//
// Requires the System.Management package:
// dotnet new console -o BackupEnvironment
// 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 Name, VariableValue, UserName FROM Win32_Environment");
var results = new List<Dictionary<string, object?>>();
foreach (ManagementObject item in searcher.Get())
{
var row = new Dictionary<string, object?>();
row["Name"] = item["Name"];
row["VariableValue"] = item["VariableValue"];
row["UserName"] = item["UserName"];
results.Add(row);
}
string timestamp = DateTime.Now.ToString("yyyyMMdd-HHmmss");
string outPath = $"environment-snapshot_{timestamp}.json";
File.WriteAllText(outPath, JsonSerializer.Serialize(results, new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine($"Snapshot of Environment Variables ({results.Count} items) saved to {outPath}");