PowerShell:可以确定文件的MIME类型吗?

时间:2012-07-28 05:21:21

标签: .net powershell

PowerShell可以确定给定文件的类型吗?例如,如果我向它传递C:\Foo.zip的路径,我可以确定该路径上的文件实际上是一个zip文件而不是其他东西吗?

4 个答案:

答案 0 :(得分:6)

如果您使用的是.NET 4.5+,则可以使用静态方法System.Web.MimeMapping.GetMimeMapping

> Add-Type -AssemblyName "System.Web"
> [System.Web.MimeMapping]::GetMimeMapping("C:\foo.zip")
application/x-zip-compressed

归功于this answer关于.NET的类似问题。


编辑:误读了这个问题。 GetMimeMapping按扩展名返回MIME类型,它不会分析内容。

答案 1 :(得分:5)

与其他Windows操作系统一样,PowerShell只根据扩展名猜测文件类型。

但是,有第三方文件类型的猜测程序,实际上是查看文件内容的程序。

有一个truly excellent answer to this question over on SuperUser。热门推荐包括File for WindowsTrID

答案 2 :(得分:3)

您可以从注册表中获取mime类型。不幸的是,HKEY_CURRENT_USER配置单元不会自动映射为驱动器,因此您必须首先检查它。

function Get-MimeType()
{
  param($extension = $null);
  $mimeType = $null;
  if ( $null -ne $extension )
  {
    $drive = Get-PSDrive HKCR -ErrorAction SilentlyContinue;
    if ( $null -eq $drive )
    {
      $drive = New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
    }
    $mimeType = (Get-ItemProperty HKCR:$extension)."Content Type";
  }
  $mimeType;
}

以下是一个示例用法

PS> Get-MimeType -extension .zip
application/x-zip-compressed

-Joe

答案 3 :(得分:0)

$ext = ".exe"
$null = New-PSDrive HKCR Registry HKEY_CLASSES_ROOT -ea 0
$mime = (gp HKCR:$ext)."Content Type"
write-host $ext $mime