如何使用POWERSHELL在IIS6网站中设置MimeTypes?

时间:2010-06-02 13:17:43

标签: powershell iis-6 wmi

我希望能够在PowerShell中复制这个adsutil.vbs行为:

cscript adsutil.vbs set W3SVC/$(ProjectWebSiteIdentifier)/MimeMap  
                                                        ".pdf,application/pdf"

我已经获得了网站对象:

$website  = gwmi -namespace "root\MicrosoftIISv2" -class "IISWebServerSetting" 
                                        -filter "ServerComment like '%$name%'"
if (!($website -eq $NULL)) { 
    #add some mimetype
}

并列出MimeMap集合:

([adsi]"IIS://localhost/MimeMap").MimeMap

任何人都知道如何填写空白以便我可以在现有的IIS6网站上添加mimetypes吗?

2 个答案:

答案 0 :(得分:2)

在经历了很多挫折和研究之后,这就是我提出的解决方案......

a)抓住COM DLL“Interop.IISOle.dll”并将其放在容易引用的地方 (例如,在虚拟项目中引用COM组件“Active DS IIS Namespace Provider”,从bin文件夹中构建并获取DLL)

b)

function AddMimeType ([string] $websiteId, [string] $extension, 
                                                        [string] $application)
{
    [Reflection.Assembly]::LoadFile("yourpath\Interop.IISOle.dll") | Out-Null;
    $directoryEntry = New-Object System
                      .DirectoryServices
                      .DirectoryEntry("IIS://localhost/W3SVC/$websiteId/root");
    try {
        $mimeMap = $directoryEntry.Properties["MimeMap"]

        $mimeType = New-Object "IISOle.MimeMapClass";
        $mimeType.Extension = $extension
        $mimeType.MimeType = $application

        $mimeMap.Add($mimeType)
        $directoryEntry.CommitChanges()
        } 
    finally {
        if ($directoryEntry -ne $null) {
            if ($directoryEntry.psbase -eq $null) {
                $directoryEntry.Dispose()
            } else {
                $directoryEntry.psbase.Dispose()
            }
        }
    }
}

c)样品用法:

AddMimeType "123456" ".pdf" "application/pdf"

参考文献:Can I setup an IIS MIME type in .NET?

答案 1 :(得分:0)

我有同样的问题。 Interop.IISOle.dll的替代方法是使用InvokeMember设置COM绑定。

$adsiPrefix = "IIS://$serverName"
$iisPath = "W3SVC"
$iisADSI = [ADSI]"$adsiPrefix/$iisPath"

$site = $iisADSI.Create("IISWebServer", $script:webSiteNumber)

$xapMimeType = New-Object -comObject MimeMap
    SetCOMProperty $xapMimeType "Extension" ".xap"
    SetCOMProperty $xapMimeType "MimeType" "application/x-silverlight-app"
    $site.Properties["MimeMap"].Add($xapMimeType)

    $site.SetInfo()
    $site.CommitChanges()

function SetCOMProperty($target, $member, $value) {
    $target.psbase.GetType().InvokeMember($member, [System.Reflection.BindingFlags]::SetProperty, $null, $target, $value)        
}