Powershell读取大文件的元数据

Ale*_*lex 0 powershell metadata

我有一个脚本循环遍历我拍摄的大量图像并读取焦距和相机模型,显示焦距和总数的图形(这对于帮助确定下一个镜头购买非常有用,但除此之外要点).

这对于10 MB以下的JPG图像来说绝对可以正常工作,但只要它接近20 MB的RAW文件(如Canon的CR2格式),它就会吐出"Out of Memory"错误.

有没有办法在Powershell中增加内存限制,或者只是在不加载整个文件的情况下读取文件的元数据..?

这就是我目前使用的:

# load image by statically calling a method from .NET
$image = [System.Drawing.Imaging.Metafile]::FromFile($file.FullName)

# try to get the ExIf data (silently fail if the data can't be found)
# http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
try
{
  # get the Focal Length from the Metadata code 37386
  $focalLength = $image.GetPropertyItem(37386).Value[0]
  # get model data from the Metadata code 272
  $modelByte = $image.GetPropertyItem(272)
  # convert the model data to a String from a Byte Array
  $imageModel = $Encode.GetString($modelByte.Value)
  # unload image
  $image.Dispose()
}
catch
{
  #do nothing with the catch
}
Run Code Online (Sandbox Code Playgroud)

我试过在这里使用解决方案:http://goo.gl/WY7Rg但CR2文件只返回任何属性的空白...

任何帮助非常感谢!

小智 5

问题是当发生错误时图像对象没有被处理掉.发生错误时,执行退出try块,这意味着Dispose调用永远不会执行,并且永远不会返回内存.

要解决此问题,您必须将$image.Dispose()调用放在finallytry/catch结尾处的块中.像这样

try
{
  /* ... */
}
catch
{
  #do nothing with the catch
}
finally
{
  # ensure image is always unloaded by placing this code in a finally block
  $image.Dispose()
}
Run Code Online (Sandbox Code Playgroud)