我使用这个远程 WMI 查询:
object idleResult = Functions.remoteWMIQuery(machinename, "", "", "Select CreationDate From Win32_Process WHERE Name = \"logonUI.exe\"", "CreationDate", ref wmiOK);
Logonui.exe 是锁屏。在业务环境中,大多数系统会在用户空闲时锁定。
您可以像这样以 DateTime 格式翻译结果
DateTime idleTime = Functions.ParseCIM_DATETIME((string)idleResult);
ParseCIM_DATETIME 是这个功能:
public static DateTime ParseCIM_DATETIME(string date)
{
//datetime object to store the return value
DateTime parsed = DateTime.MinValue;
//check date integrity
if (date != null && date.IndexOf('.') != -1)
{
//obtain the date with miliseconds
string newDate = date.Substring(0, date.IndexOf('.') + 4);
//check the lenght
if (newDate.Length == 18)
{
//extract each date component
int y = Convert.ToInt32(newDate.Substring(0, 4));
int m = Convert.ToInt32(newDate.Substring(4, 2));
int d = Convert.ToInt32(newDate.Substring(6, 2));
int h = Convert.ToInt32(newDate.Substring(8, 2));
int mm = Convert.ToInt32(newDate.Substring(10, 2));
int s = Convert.ToInt32(newDate.Substring(12, 2));
int ms = Convert.ToInt32(newDate.Substring(15, 3));
//compose the new datetime object
parsed = new DateTime(y, m, d, h, mm, s, ms);
}
}
//return datetime
return parsed;
}
远程 WMI 查询功能如下:
public static object remoteWMIQuery(string machine, string username, string password, string WMIQuery, string property, ref bool jobOK)
{
jobOK = true;
if (username == "")
{
username = null;
password = null;
}
// Configure the connection settings.
ConnectionOptions options = new ConnectionOptions();
options.Username = username; //could be in domain\user format
options.Password = password;
ManagementPath path = new ManagementPath(String.Format("\\\\{0}\\root\\cimv2", machine));
ManagementScope scope = new ManagementScope(path, options);
// Try and connect to the remote (or local) machine.
try
{
scope.Connect();
}
catch (ManagementException ex)
{
// Failed to authenticate properly.
jobOK = false;
return "Failed to authenticate: " + ex.Message;
//p_extendederror = (int)ex.ErrorCode;
//return Status.AuthenticateFailure;
}
catch (System.Runtime.InteropServices.COMException)
{
// Unable to connect to the RPC service on the remote machine.
jobOK = false;
return "Unable to connect to RPC service";
//p_extendederror = ex.ErrorCode;
//return Status.RPCServicesUnavailable;
}
catch (System.UnauthorizedAccessException)
{
// User not authorized.
jobOK = false;
return "Error: Unauthorized access";
//p_extendederror = 0;
//return Status.UnauthorizedAccess;
}
try
{
ObjectQuery oq = new ObjectQuery(WMIQuery);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, oq);
foreach (ManagementObject queryObj in searcher.Get())
{
if (property != null)
{
return queryObj[property];
}
else return queryObj;
}
}
catch (Exception e)
{
jobOK = false;
return "Error: " + e.Message;
}
return "";
}