You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell加载System.Web获取MIME类型:ISE正常控制台报错

解决PowerShell.exe中无法找到[System.Web.MimeMapping]类型的问题

问题原因

PowerShell ISE与PowerShell.exe的运行环境存在差异:ISE会自动加载部分依赖程序集,而PowerShell.exe中System.Web程序集的加载可能受系统配置(如是否安装IIS/ASP.NET组件)影响,导致无法定位System.Web.MimeMapping类型。

解决方案

方案一:显式加载System.Web程序集

通过指定System.Web.dll的完整路径来强制加载程序集,适用于已安装.NET Framework和ASP.NET组件的系统:

$FilePath = "C:\users\Daniel\Desktop\test.pdf"

# 根据进程位数选择对应的程序集路径
$webAssemblyPath = if ([Environment]::Is64BitProcess) {
    "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Web.dll"
} else {
    "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll"
}
Add-Type -Path $webAssemblyPath

$DocExtension = [System.IO.Path]::GetExtension($FilePath)
$DocMimeType  = [System.Web.MimeMapping]::GetMimeMapping($DocExtension)

Write-Output "Extension: $DocExtension `nMIME-type: $DocMimeType"

方案二:使用Windows注册表获取MIME类型(推荐)

直接读取系统注册表中存储的MIME映射,无需依赖System.Web程序集,兼容性更强:

$FilePath = "C:\users\Daniel\Desktop\test.pdf"
$DocExtension = [System.IO.Path]::GetExtension($FilePath)

# 读取扩展名对应的注册表项中的Content Type
$regPath = "HKLM:\SOFTWARE\Classes\$DocExtension"
$DocMimeType = (Get-ItemProperty -Path $regPath -Name 'Content Type' -ErrorAction SilentlyContinue).'Content Type'

# 未找到时使用默认二进制流类型
if (-not $DocMimeType) {
    $DocMimeType = "application/octet-stream"
}

Write-Output "Extension: $DocExtension `nMIME-type: $DocMimeType"

该方案利用Windows系统原生的MIME配置,不受PowerShell运行环境差异影响,适用于所有Windows PowerShell版本。

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:34:50