如何用C#获取执行shutdown命令后的电脑准确关机时间?
问题描述
在命令行执行shutdown -s -t 8000命令后,需要编写C#代码获取电脑的准确关机时间。尝试通过Windows事件日志查询EventID为1074的事件,但日志仅记录命令执行时间和执行者;使用schtasks未找到相关任务(因为shutdown.exe不会在任务计划程序中创建任务);曾看到提及winlogon进程的文章,但未说明如何读取其标志。现需解决如何获取执行该命令后的准确关机时间。
解决方案
方法一:从运行的shutdown.exe进程提取参数
当shutdown -s -t <秒数>命令执行后,shutdown.exe进程会持续运行直到关机(或被取消)。通过WMI查询该进程的命令行参数和启动时间,即可计算出关机时间。
代码示例:
using System; using System.Management; public static DateTime? GetShutdownTimeFromRunningProcess() { try { // WMI查询shutdown.exe进程的命令行和创建时间 var searcher = new ManagementObjectSearcher( "SELECT CommandLine, CreationDate FROM Win32_Process WHERE Name = 'shutdown.exe'" ); foreach (var process in searcher.Get()) { string cmdLine = process["CommandLine"]?.ToString(); if (string.IsNullOrWhiteSpace(cmdLine)) continue; // 解析-t参数后的秒数 int timeoutSec = 0; string[] args = cmdLine.Split(' ', StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-t", StringComparison.OrdinalIgnoreCase) && i + 1 < args.Length) { int.TryParse(args[i + 1], out timeoutSec); break; } } if (timeoutSec <= 0) continue; // 解析WMI格式的创建时间 string createDateStr = process["CreationDate"]?.ToString(); if (DateTime.TryParseExact( createDateStr, "yyyyMMddHHmmss.ffffffzzz", null, System.Globalization.DateTimeStyles.None, out DateTime createTime )) { return createTime.AddSeconds(timeoutSec); } } } catch (Exception ex) { // 实际使用中可根据需求处理异常(如权限不足) Console.WriteLine($"查询进程失败: {ex.Message}"); } return null; }
方法二:从事件日志提取命令参数
EventID为1074的系统事件描述中,会包含shutdown.exe的完整命令行参数。通过解析该事件的消息内容,提取-t后的秒数,结合事件的创建时间即可计算关机时间。
代码示例:
using System; using System.Diagnostics.Eventing.Reader; using System.Text.RegularExpressions; public static DateTime? GetShutdownTimeFromEventLog() { int targetEventId = 1074; string query = $"*[System/EventID={targetEventId}]"; EventLogQuery logQuery = new EventLogQuery("System", PathType.LogName, query); try { using (EventLogReader reader = new EventLogReader(logQuery)) { EventRecord eventRecord; // 遍历事件,取最新的一条关机命令记录 while ((eventRecord = reader.ReadEvent()) != null) { string eventMsg = eventRecord.FormatDescription(); DateTime eventTime = eventRecord.TimeCreated.Value; // 正则匹配-t后的秒数 Match timeoutMatch = Regex.Match(eventMsg, @"-t\s+(\d+)", RegexOptions.IgnoreCase); if (timeoutMatch.Success && int.TryParse(timeoutMatch.Groups[1].Value, out int timeoutSec)) { if (timeoutSec > 0) { return eventTime.AddSeconds(timeoutSec); } } } } } catch (Exception ex) { Console.WriteLine($"查询事件日志失败: {ex.Message}"); } return null; }
说明
- 方法一适用于
shutdown.exe进程仍在运行的场景(未被取消关机); - 方法二适用于进程已退出,但事件日志已记录该关机命令的场景;
- 若关机命令已被取消(如执行
shutdown -a),则不会有实际的关机时间,需结合其他事件(如EventID 1075)判断。
内容的提问来源于stack exchange,提问作者FaceHoof
相关产品推荐
相关产品推荐

