使用管理类添加一个ScriptMap对象

问题描述:

我已经问过一个相关的问题,但遗憾的是答案虽然正确,但并未真正解决我的问题。使用管理类添加一个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的工作代码?

我发现从零开始创建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

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(); 
    }