微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ForEach-Object循环中的Powershell“Move-Item:该进程无法访问该文件,因为它正在被另一个进程使用”

如何解决ForEach-Object循环中的Powershell“Move-Item:该进程无法访问该文件,因为它正在被另一个进程使用”

我正在尝试搜索我所有的照片文件夹,并将任何具有特定尺寸的图像(1125x2436 - 即 iPhone 上的屏幕截图)移动到一个单独的文件夹中,我可以查看并很可能在之后删除文件夹。

我从 Writing a script to copy images of certain dimensions获取了脚本,如下所示。这会复制图像,但是当我将其更改为 Move-Item 时,我收到“Move-Item:该进程无法访问该文件,因为它正被另一个进程使用。”我猜是因为它仍然被 ForEach-Object 循环中的 System.Drawing.Image 打开。

删除或传递给变量以在循环外使用之前,我尝试调整它并关闭图像,但没有成功。

这就是我所拥有的

$source = Get-Location
$destination = "C:\Users\USER\Desktop\Output\"
$maxWidth    = 1125
$maxHeight   = 2436

# if the destination path does not exist,create it
if (!(Test-Path -Path $destination -PathType Container)) {
    New-Item -Path $destination -ItemType Directory | Out-Null
}

# Add System.Drawing assembly
Add-Type -AssemblyName System.Drawing

Get-ChildItem -Path $source -File -Recurse | ForEach-Object {
    # capture the full filename so we can use it in the catch block
    $fileName = $_.FullName
    # Open image file
    try {
        $img = [System.Drawing.Image]::FromFile($fileName)
        # use '-ge'  if you want to copy files with a width and/or height Greater Or Equal To the max dimensions
        # use '-and' if you want to copy files where both the Width and the Height exceed the max dimensions
        if ($img.Width -eq $maxWidth -and $img.Height -eq $maxHeight) {
    $_ | Move-Item -Verbose -Destination $destination -Force
        }
    } 
    catch {
        Write-Warning "Could not open file '$fileName' - Not an image file?"
    }
}

我应该说我对 powershell 和发布 stackoverflow 很感兴趣,因此非常感谢任何建议。提前致谢。

解决方法

再深入挖掘后,就像在移动前添加 $img.dispose() 一样简单。

回答对其他人有用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。