1

我刚刚写了3个不同的代码。其中一个工作正常。但是另外两个,不要工作并抛出一个ManagementException消息:

此方法未在任何类中实现

这是可以正常工作的代码:

string ComputerName = "localhost";
ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);

Scope.Connect();

string WQL = String.Format("SELECT * FROM Win32_Volume");
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

foreach (ManagementObject ClassInstance in Searcher.Get())
{
    ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Defrag");
    ManagementBaseObject outParams = ClassInstance.InvokeMethod("Defrag", inParams, null);
    Console.WriteLine("{0,-35} {1,-40}", "DefragAnalysis", outParams["DefragAnalysis"]);
    Console.WriteLine("{0,-35} {1,-40}", "ReturnValue", outParams["ReturnValue"]);
}

Console.ReadLine();

这是不工作并引发异常的代码(请参阅基本相同的代码) 改变的一件事是使用的 WMI 类。异常发生在 InvokeMethod 上。

string ComputerName = "localhost";
ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
string WQL = String.Format("SELECT * FROM Win32_PnPEntity");
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

foreach (ManagementObject ClassInstance in Searcher.Get())
{                
    ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Disable");
    ManagementBaseObject outParams = ClassInstance.InvokeMethod("Disable", inParams, null);
    Console.WriteLine("{0,-35} {1,-40}", "ReturnValue", outParams["ReturnValue"]);
    Console.WriteLine("{0,-35} {1,-40}", "rebootNeeded", outParams["rebootNeeded"]);
}

Console.ReadLine();

我还尝试使用“重置”方法而不是“禁用”方法。这没用。但这一次,异常发生在GetMethodParameters. 它说这个方法没有在任何类中实现。

string ComputerName = "localhost";
ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
string WQL = String.Format("SELECT * FROM Win32_PnPEntity");
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

foreach (ManagementObject ClassInstance in Searcher.Get())
{                
    ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Reset");
    ManagementBaseObject outParams = ClassInstance.InvokeMethod("Reset", inParams, null);
    Console.WriteLine("{0,-35} {1,-40}", "ReturnValue", outParams["ReturnValue"]);
    Console.WriteLine("{0,-35} {1,-40}", "rebootNeeded", outParams["rebootNeeded"]);
}

Console.ReadLine();

我需要一个启用和禁用 PNP 设备的代码,此外,我需要使用 WMI 类来保持与其余代码相同的标准,所以我需要使用 namespace System.Management

4

1 回答 1

0

禁用设备的代码是正确的,但您需要以管理员权限运行它。如果没有管理员权限,我会收到 System.Management.ManagementException 'Generic failure'。

于 2019-09-18T12:08:35.977 回答