-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
91 lines (77 loc) · 2.74 KB
/
Program.cs
File metadata and controls
91 lines (77 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Copyright (c) Microsoft Corporation. All rights reserved.
using System.Diagnostics;
using System.Text.Json;
// Step 1: Run powercfg /sleepstudy /json
Console.WriteLine("Running powercfg /sleepstudy /json...");
string sleepStudyJson = RunPowerCfgSleepStudy();
if (string.IsNullOrEmpty(sleepStudyJson))
{
Console.Error.WriteLine("No sleep study data returned. Make sure to run as Administrator.");
return 1;
}
// Step 2: Parse and collect all PowerSnapData entries
using var doc = JsonDocument.Parse(sleepStudyJson);
var root = doc.RootElement;
var writeOptions = new JsonSerializerOptions { WriteIndented = true };
var events = new List<JsonElement>();
if (root.TryGetProperty("ScenarioInstances", out var scenarios) && scenarios.ValueKind == JsonValueKind.Array)
{
foreach (var scenario in scenarios.EnumerateArray())
{
if (scenario.TryGetProperty("PowerSnapData", out var powerSnapData) && powerSnapData.ValueKind == JsonValueKind.Array)
{
foreach (var powerSnapEvent in powerSnapData.EnumerateArray())
{
events.Add(powerSnapEvent.Clone());
}
}
}
}
// Step 3: Write all events to powersnap-events.json
string outputPath = "powersnap-events.json";
string json = JsonSerializer.Serialize(events, writeOptions);
File.WriteAllText(outputPath, json);
Console.WriteLine($"Total PowerSnap events: {events.Count}");
Console.WriteLine($"Output written to: {Path.GetFullPath(outputPath)}");
return 0;
// ─── Helper methods ───
static string RunPowerCfgSleepStudy()
{
string outputFile = Path.Combine(Path.GetTempPath(), "sleepstudy-temp.json");
try
{
using var process = new Process();
process.StartInfo = new ProcessStartInfo
{
FileName = "powercfg",
Arguments = $"/sleepstudy /json /output \"{outputFile}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
string error = process.StandardError.ReadToEnd();
throw new Exception($"powercfg failed with exit code {process.ExitCode}: {error}");
}
if (File.Exists(outputFile))
{
return File.ReadAllText(outputFile);
}
else
{
throw new Exception("Sleep study report was not generated. The command may have failed.");
}
}
finally
{
if (File.Exists(outputFile))
{
try { File.Delete(outputFile); }
catch { Console.Error.WriteLine($"Warning: Could not delete temp file: {outputFile}"); }
}
}
}