powershell - ForEach-Object循环中的Powershell“Move-Item:该进程无法访问该文件,因为它正被另一个进程使用”
问题描述
我正在尝试搜索我所有的照片文件夹,并且任何具有特定尺寸的图像(1125x2436 - 即 iphone 上的屏幕截图)都被移动到一个单独的文件夹中,我可以查看并很可能在之后删除。
我已经从编写脚本中获取脚本以复制某些尺寸的图像,如下所示。这会复制图像,但是当我将其更改为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()
在移动之前添加一样简单。
回答以防对其他人有用。
推荐阅读
- asp.net-core - 无法在生产机器上启动 Kestrel IServiceCollection 仍然为空
- c# - 如何将外部 txt 文件的行插入到 Visual c# 中的 domainupdown 项中?
- r - 在 R 中使用 plotly 时,地图未显示在 RStudio 查看器中
- java - MongoDB Java API 读取速度慢
- javascript - 我可以使用 parseInt 来解决这个问题吗?控制流
- java - 非 void 方法调用而不在 Java 中分配返回值
- asp.net - asp.net 同时覆盖文件
- ios - 有没有办法在不使用 SNMP 的情况下检测连接的主机设备的软件版本或内核版本
- python - 如何有效地迭代 pandas DataFrame 并在这些值上增加 NumPy 数组?
- ios - 覆盖 UITableViewController 中的 setEdit:调用从何而来?