string ComputerName = serverName;
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";
Conn.Password = "";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect(); // CRASH HERE
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_Process Where Name='" + processName + "'");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
显示的消息是:
价值不在预期范围内。
答案 0 :(得分:2)
这很可能与错误的凭据或权限不足有关。在您的情况下,没有提供用户名 - 我很确定您无法传递空用户名。用于WMI查询的用户名/密码必须存在于远程PC上(此外,用户必须具有足够的权限)。
如果您想使用在本地PC上运行代码的相同用户名/密码,则应省略整个ConnectionOptions部分:
//ConnectionOptions Conn = new ConnectionOptions();
//Conn.Username = "";
//Conn.Password = "";
//Conn.Authority = "ntlmdomain:DOMAIN";
我尝试了你的代码(添加了最后4行进行测试),它出现了与你相同的错误。一旦我添加了用户名和密码,一切运行正常。
string ComputerName = "10.1.2.3";
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "Administrator";
Conn.Password = "pass123";
//Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect(); // CRASH HERE
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_Process Where Name='" + "cmd.exe" + "'");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
ManagementObjectCollection queryCollection = Searcher.Get();
foreach (var item in queryCollection)
Console.WriteLine(item["Description"]);
Console.Read();
我也尝试了相同的代码,其中有关于注释掉的ConnectionOptions的部分,它也有效。但请注意,根据我之前的描述,我必须在远程PC上创建一个用户,该用户具有与我在本地PC上登录的用户相同的凭据。
希望这有帮助。
编辑:同样根据Maximilian Gerhardt评论,跳过NULL这一行:
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);