【问题标题】:Powershell "Move-Item : The process cannot access the file because it is being used by another process" in ForEach-Object loopForEach-Object循环中的Powershell“Move-Item:该进程无法访问该文件,因为它正被另一个进程使用”
【发布时间】:2021-05-11 10:02:40
【问题描述】:

我正在尝试搜索我所有的照片文件夹,并且任何具有特定尺寸(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 很感兴趣,因此非常感谢任何建议。提前致谢。

【问题讨论】:

  • 你能只运行$_的选择吗?它包含什么?
  • 我不知道你要我做什么对不起。在单独的行上运行它?我什至不确定 $_ 的功能是什么。

标签: powershell file move photo system.drawing


【解决方案1】:

经过一番挖掘后,就像在移动之前添加$img.dispose() 一样简单。

回答对其他人有用。

【讨论】:

  • 仅供参考,很好,你找到了这个。然而,请记住,这不仅仅是使用 Move-Item 时的图像,使用 Remove-Item 也应该发生同样的事情。这不是 PowerShell 问题;只要文件句柄处于活动状态,Windows 就无法移动(删除)文件。正如你所发现的,你必须首先释放它们。即使使用 Rename-Item,它也是一个两步过程,如果在同一个文件夹中,取决于命名细节,或者您最终调用核心 DLL 以避免这种情况。
猜你喜欢
  • 2022-11-22
  • 1970-01-01
  • 2021-04-29
  • 2010-12-10
相关资源
最近更新 更多