Q:

How to delete a file that is being used by the Powershell script itself?

I'm trying to loop over all the pictures in a given directory, checking their size and dimensions. When some property dismatches my constraints, i want to delete the file right away. Otherwise i want to perform some other action.
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"
}

I expect a picture that is too small in dimensions or size to be deleted with the according output. And if a picture matches all requirements, i want to see the output "other action"
It works except for the deletion, which gives me this error:

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.
In PowerShell\ADPhotoHandler.ps1:27 Zeichen:9
+         Remove-Item -Force $fname
+         ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (\tooSmall2.PNG:FileInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

A:

The System.Drawing.Image.FromFile() documentation states:

The file remains locked until the Image is disposed.

Therefore, call $image.Dispose() before attempting to delete the underlying file.

