关闭由 .NET 打开的文件句柄

Close a file handle opened by .NET

我正在编写一个脚本来根据 EXIF 数据重命名文件。

param([string]$path)

# http://blogs.technet.com/b/jamesone/archive/2007/07/13/exploring-photographic-exif-data-using-powershell-of-course.aspx
[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll") | out-null

function MakeString { 
    $s=""
    for ($i=0 ; $i -le $args[0].value.length; $i ++) {
        $s = $s + [char]$args[0].value[$i]
    }
    return $s
}

$files = Get-ChildItem -Path $path
foreach ($file in $files) {
    if ($file.Extension -ne ".jpg") { continue }
    if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
    $exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
    $captureDate = MakeString $exif.GetPropertyItem(36867)
    $captureDate = ($captureDate -replace ":", '-').Substring(0,19)
    $newFilename = $captureDate + " " + $file.Name.Trim()
    $file.Name + " -> " + $newFilename
    $file |Rename-Item -NewName $newFilename
}

从 EXIF 中读取日期没有问题,但是当我尝试重命名文件时出现此错误消息:

Rename-Item : The process cannot access the file because it is being used by another process.
At D:\Norwegen\RenamePhotos.ps1:25 char:12
+     $file |Rename-Item -NewName $newFilename
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Norwegen\P1270465 (1920x1433).jpg:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

当我在 ProcMon 中监视目录时,我可以看到文件关闭得相当晚:

(查看突出显示的行,它来自当前正在处理的文件条目中间的较早文件)

那么,我怎样才能关闭文件(从读取 EXIF 时可能仍然打开)以便重命名它?

我已经尝试关闭打开的文件:

Remove-Variable exif
$file.Close()

由于您只读取文件,因此调用 Dispose() 应该可以解决问题。例如

    foreach ($file in $files) {
    if ($file.Extension -ne ".jpg") { continue }
    if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
    $exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
    $captureDate = MakeString $exif.GetPropertyItem(36867)

    #Disposing object as soon as possible
    $exif.Dispose()

    $captureDate = ($captureDate -replace ":", '-').Substring(0,19)
    $newFilename = $captureDate + " " + $file.Name.Trim()
    $file.Name + " -> " + $newFilename
    $file |Rename-Item -NewName $newFilename
}