🟣 C# / .NET 6+

Backup Local User Accounts to JSON (C#)

Snapshots Local User Accounts (Win32_UserAccount) to a timestamped JSON file via System.Management and System.Text.Json.

By WindowsScripting.com · 1.3 KB
BackupUserAccountListToJson.cs
// BackupUserAccountListToJson.cs
//
// Snapshots Local User Accounts (Win32_UserAccount) to a timestamped JSON file.
//
// Requires the System.Management package:
//   dotnet new console -o BackupUserAccount
//   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, FullName, Disabled, Lockout, LocalAccount FROM Win32_UserAccount");
var results = new List<Dictionary<string, object?>>();

foreach (ManagementObject item in searcher.Get())
{
    var row = new Dictionary<string, object?>();
    row["Name"] = item["Name"];
        row["FullName"] = item["FullName"];
        row["Disabled"] = item["Disabled"];
        row["Lockout"] = item["Lockout"];
        row["LocalAccount"] = item["LocalAccount"];
    results.Add(row);
}

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

Console.WriteLine($"Snapshot of Local User Accounts ({results.Count} items) saved to {outPath}");