[如何删除Powershell脚本本身正在使用的文件? [重复]

问题描述 投票:1回答:1

此问题已经在这里有了答案:

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

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图片\ tooSmall2.PNG kann nicht entwernt werden:DerProzess kann nicht auf die Datei“ pics \ tooSmall2.PNG” zugreifen,da sie vonEinem Anderen Prozess verwendet wird。在PowerShell \ ADPhotoHandler.ps1:27 Zeichen:9中+ Remove-Item-强制$ fname+ ~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo:WriteError:(\ tooSmall2.PNG:FileInfo)[Remove-Item],IOException+ FullyQualifiedErrorId:RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
powershell delete-file
1个回答
0
投票

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

文件保持锁定,直到处理完图像。

因此,请在尝试删除基础文件之前调用System.Drawing.Image.FromFile()。>>

© www.soinside.com 2019 - 2024. All rights reserved.