使用下面的代码从本地计算机的安全日志事件中检索数据时遇到问题。我在各种计算机上测试过:本地机器是windows xp sp3。查询没有错误但返回0记录。对于远程机器,它工作得很好 有谁能给我一个解决方案? 这是代码:
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
string[] arrComputers = {".","clientN"};
foreach (string strComputer in arrComputers)
{
Console.WriteLine("==========================================");
Console.WriteLine("Computer: " + strComputer);
Console.WriteLine("==========================================");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(
"\\\\" + strComputer + "\\root\\CIMV2",
"SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security'");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_NTLogEvent instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("RecordNumber: {0}", queryObj["RecordNumber"]);
Console.WriteLine("SourceName: {0}", queryObj["SourceName"]);
Console.WriteLine("TimeGenerated: {0}", queryObj["TimeGenerated"]);
}
}
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while querying for WMI data: " + err.Message);
}
}
}
}
我明白在vbs中使用wmi查询的模拟级别可以正常工作。
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile = 'Security'" )
所以我必须翻译c#。
答案 0 :(得分:1)
好的,所以我使用我的代码关闭了这个问题。 代码是:
using System;
using System.Management;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ConnectionOptions oConn = new ConnectionOptions();
oConn.Impersonation = ImpersonationLevel.Impersonate;
oConn.EnablePrivileges = true;
string[] arrComputers = {".","clientN"};
foreach (string strComputer in arrComputers)
{
Console.WriteLine("==========================================");
Console.WriteLine("Computer: " + strComputer);
Console.WriteLine("==========================================");
ManagementObjectSearcher searcher = new ManagementObjectSearcher
(
new ManagementScope("\\\\" + strComputer + "\\root\\CIMV2", oConn),
new ObjectQuery( @"SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security'")
);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_NTLogEvent instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("RecordNumber: {0}", queryObj["RecordNumber"]);
Console.WriteLine("SourceName: {0}", queryObj["SourceName"]);
Console.WriteLine("TimeGenerated: {0}", queryObj["TimeGenerated"]);
}
}
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while querying for WMI data: " + err.Message);
}
}
}
}
答案 1 :(得分:0)
尝试使用本地计算机名而不是“。”。所以,而不是
string[] arrComputers = {".","clientN"};
你会有
string[] arrComputers = { Environment.GetEnvironmentVariable("computername"), "clientN"
};