关闭.NET打开的文件句柄

时间:2015-02-08 17:30:29

标签: powershell filelock

我正在使用脚本根据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中的目录时,我可以看到文件关闭的时间很晚:

enter image description here

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

那么,如何关闭文件(可能仍然从EXIF读取打开)所以我可以重命名它?

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

Remove-Variable exif
$file.Close()

1 个答案:

答案 0 :(得分:3)

由于您只是从文件中读取,因此调用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
}