2009-01-21 26 views
2

我已經問過一個相關的問題,但遺憾的是答案雖然正確,但並未真正解決我的問題。使用管理類添加一個ScriptMap對象

我使用ManagementClass/ManagementObject WMI API(因爲它比DirectoryEntry API更好地處理遠程管理)。我想從

中完全刪除現有腳本映射使用公共字符串格式解決方案似乎適用於VBS,但不適用於ManagementClass API。所以,我一直在嘗試寫一些能夠創建正確的腳本映射對象數組的東西,例如

foreach (var extension in extensions) { 
     var scriptMap = scriptMapClass.CreateInstance(); 
     SetWmiProperty(scriptMap, "ScriptMap.Extensions", "." + extension); 

不幸的是,它似乎不可能實現函數SetWmiProperty。如果我嘗試以下方法

wmiObject.Properties.Add(propertyName, CimType.SInt32); 

我得到「由於對象的當前狀態,操作無效」。另一方面,如果我只是試圖設置屬性,我會被告知該屬性不存在。 scriptMap類具有路徑「ScriptMap」,這是現有對象顯示的內容。

有沒有人有任何使用ManagementClass API操作ScriptMaps的工作代碼?

回答

1

我發現從零開始創建WMI對象非常困難。更容易克隆()您從系統查詢的現有對象,然後對其進行修改。這是我最近寫的一個處理ScriptMaps的函數。它是在Powershell中,而不是C#,但它的想法是一樣的:

function Add-AspNetExtension 
{ 
    [CmdletBinding()] 
    param (
     [Parameter(Position=0, Mandatory=$true)] 
     [psobject] $site # IIsWebServer custom object created with Get-IIsWeb 
     [Parameter(ValueFromPipeline=$true, Mandatory=$true)] 
     [string] $extension 
    ) 

    begin 
    { 
     # fetch current mappings 
     # without the explicit type, PS will convert it to an Object[] when you use the += operator 
     [system.management.managementbaseobject[]] $maps = $site.Settings.ScriptMaps 

     # whatever the mapping is for .aspx will be our template for mapping other things to ASP.NET 
     $template = $maps | ? { $_.Extensions -eq ".aspx" } 
    } 

    process 
    { 
     $newMapping = $template.Clone() 
     $newMapping.Extensions = $extension 
     $maps += newMapping 
    } 

    end 
    { 
     $site.Settings.ScriptMaps = $maps 
    } 
} 
+0

正是我所需要的。謝謝你這麼多:這解決了我兩年來一直非常煩惱的問題。 – 2009-04-30 14:27:30

2

Richard Berg概述的C#示例技術。

static void ConfigureAspNet(ManagementObject virtualDirectory, string version, string windowsLocation, IEnumerable<string> extensions) 
    { 
     var scriptMaps = virtualDirectory.GetPropertyValue("ScriptMaps"); 
     var templateObject = ((ManagementBaseObject[])scriptMaps)[0]; 
     List<ManagementBaseObject> result = new List<ManagementBaseObject>(); 
     foreach (var extension in extensions) { 
      var scriptMap = (ManagementBaseObject) templateObject.Clone(); 
      result.Add(scriptMap); 
      if (extension == "*") 
      { 
       scriptMap.SetPropertyValue("Flags", 0); 
       scriptMap.SetPropertyValue("Extensions", "*"); 
      } else 
      { 
       scriptMap.SetPropertyValue("Flags", 5); 
       scriptMap.SetPropertyValue("Extensions", "." + extension); 
      } 
      scriptMap.SetPropertyValue("IncludedVerbs", "GET,HEAD,POST,DEBUG"); 
      scriptMap.SetPropertyValue("ScriptProcessor", 
       string.Format(@"{0}\microsoft.net\framework\{1}\aspnet_isapi.dll", windowsLocation, version)); 
     } 
     virtualDirectory.SetPropertyValue("ScriptMaps", result.ToArray()); 
     virtualDirectory.Put(); 
    } 
相關問題