首页 > 解决方案 > 如何删除 Powershell 脚本本身正在使用的文件?

问题描述

我正在尝试遍历给定目录中的所有图片,检查它们的大小和尺寸。当某些属性与我的约束不匹配时,我想立即删除该文件。否则我想执行一些其他操作。

Add-Type -AssemblyName System.Drawing

$maxFileSizeKB = 100
$minPicWidth = 500
$minPicHeight = 500

foreach ($file in Get-ChildItem -Path ..\pics) {
    $fname = $file.fullname
    $fsizeKB = $file.length/1KB
    $image = [System.Drawing.Image]::FromFile($file.FullName)
    $iWidth = $image.width
    $iHeight = $image.height
    $fLastWrite = $file.LastWriteTime

    if( $fsizeKB -gt $maxFileSizeKB -or
        $iWidth -lt $minPicWidth -or
        $iHeight -lt $minPicHeight) {
        Write-Host "`tDoes'nt match criteria - deleting and continueing with next Image ..."
        Remove-Item -Force $fname
        continue
    }
    Write-Host "other action"
}

我希望通过相应的输出删除尺寸或尺寸太小的图片。如果图片符合所有要求,我想查看输出“其他操作”

它的工作原理是删除,这给了我这个错误:

Remove-Item : Das Element pics\tooSmall2.PNG kann nicht entfernt werden: Der
Prozess kann nicht auf die Datei "pics\tooSmall2.PNG" zugreifen, da sie von
einem anderen Prozess verwendet wird。
在 PowerShell\ADPhotoHandler.ps1:27 Zeichen:9
+ 删除项目 -Force $fname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (\tooSmall2.PNG:FileInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

标签: powershelldelete-file

解决方案


System.Drawing.Image.FromFile()文档指出:

该文件保持锁定状态,直到图像被释放。

因此,$image.Dispose()在尝试删除基础文件之前调用。


推荐阅读