2012-07-11 18 views
0

我想將下面的代碼轉換爲C#使用WMI和System.Management庫。任何人都能找到正確的方向或提供一些幫助。轉換JScript WMI C#

var IMPORT_CHILDREN = 0; // Recursively imports the subkeys of the specified key. 
var IMPORT_INHERITED = 1; // Imports the inherited properties of the keys. 
var IMPORT_NODE_ONLY = 2; // Does not import subkeys from the specified file. 
var IMPORT_MERGE = 4; // Merges the imported keys into the existing configuration instead of completely replacing what is there. 

var strPassword = "ExportingPassw0rd"; 
var strFilePath = "C:\\exported.xml"; 
var strSourceMetabasePath = "/lm/logging/custom logging"; // As represented in the metabase.xml file. 
var strDestinationMetabasePath = "/lm/logging/custom logging"; // Can be different from the source. 
var intFlags = IMPORT_NODE_ONLY | IMPORT_INHERITED; // Import only the node with inherited properties. 

// Make connections to WMI, to the IIS namespace on MyMachine, and to the IIsComputer object. 
var locatorObj = new ActiveXObject("WbemScripting.SWbemLocator"); 
var providerObj = locatorObj.ConnectServer("MyMachine", "root/MicrosoftIISv2"); 
var computerObj = providerObj.get("IIsComputer='LM'"); 

// Call export method from the computer object. 
computerObj.Import(strPassword, strFilePath, strSourceMetabasePath, strDestinationMetabasePath, intFlags); 

// Print results. 
WScript.Echo("Imported the node in " + strFilePath + " to " + strDestinationMetabasePath); 
+0

http://whathaveyoutried.com? – 2012-07-11 08:31:51

回答

1

.NET 4.0:

dynamic locatorObj = Activator.CreateInstance(Type.GetTypeFromProgID(("WbemScripting.SWbemLocator"))); 
    dynamic providerObj = locatorObj.ConnectServer("MyMachine", "root/MicrosoftIISv2"); 
    dynamic computerObj = providerObj.get("IIsComputer='LM'"); 

    computerObj.Import(strPassword, strFilePath, strSourceMetabasePath, strDestinationMetabasePath, intFlags); 

.NET 3.5及以下:

var locatorObj = Activator.CreateInstance(Type.GetTypeFromProgID(("WbemScripting.SWbemLocator"))); 
    var providerObj = locatorObj._I("ConnectServer", "MyMachine", "root/MicrosoftIISv2"); 
    var computerObj = providerObj._I("get", "IIsComputer='LM'"); 

    computerObj._I("Import", strPassword, strFilePath, strSourceMetabasePath, strDestinationMetabasePath, intFlags); 


public static class ReflectionHlp 
{ 
    public static object _I(this object item, string name, params object[] args) 
    { 
    if (item == null) 
     return null; 
    return item.GetType().InvokeMember(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, item, args); 
    } 

} 
+0

嘿@DarkGray!這是一個很好的解決方案,我不幸受到3.5的使用限制,並且沒有動態訪問權限。你可能有3.5的解決方案? – Jonathan 2012-07-11 07:53:28

+0

@Jonathan現在檢查 – 2012-07-11 08:31:23

+0

你是我的朋友!它真的很感激! – Jonathan 2012-07-11 09:26:16