10

Is it possible for PowerShell to determine what a given file's type is? For example, if I pass it a path of C:\Foo.zip, can I have it determine that the file at that path is, in fact, a zip file and not something else?

Nick
  • 8,049
  • 18
  • 63
  • 107

4 Answers4

12

If you have .NET 4.5+, you can use the static method System.Web.MimeMapping.GetMimeMapping:

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

Credit goes to this answer to a similar question about .NET.


Edit: Misread the question. GetMimeMapping returns the MIME type by extension, it doesn't analyze the contents.

Community
  • 1
  • 1
Helen
  • 87,344
  • 17
  • 243
  • 314
7

PowerShell, like rest of the Windows operating system, merely guesses the file type based on the extension.

However, there are third-party file type guesser programs out there, ones that actually look at the contents of the file.

There is a truly excellent answer to this question over on SuperUser. Top recommendations include File for Windows and TrID.

Community
  • 1
  • 1
Martin Burch
  • 2,726
  • 4
  • 31
  • 59
3

You can get the mime types from the registry. Unfortunately the HKEY_CURRENT_USER hive isn't auto-mapped as a drive so you'll have to put a check in for that first.

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

Here's an example usage

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

-Joe

Joe Pruitt
  • 39
  • 2
  • 3
    This doesn't actually test the contents of the target file, it simply reads the extension and looks up the file type relationship from the OS. – Ro Yo Mi Mar 27 '14 at 20:53
1
$ext = ".exe"
$null = New-PSDrive HKCR Registry HKEY_CLASSES_ROOT -ea 0
$mime = (gp HKCR:$ext)."Content Type"
write-host $ext $mime
  • 4
    Please elaborate on your answer (tell us _what_ the issue is, and _how_ this code fixes that issue). Code-only answers are less educational and of limited use. – Erik A Sep 09 '17 at 16:57
  • 1
    You should give more context/explanation for the code, especially since there are already several high-quality answers. Please read the site [tour] as well as [answer]. – EJoshuaS - Stand with Ukraine Sep 09 '17 at 22:37