Vijay Jagdale
Vijay Jagdale

Reputation: 2669

PowerShell releasing the file lock created by the last criteria test

I need to select images based on size, width, and datemodified, and move them, as well as rename them. Here is my script so far:

Add-Type -Assembly System.Drawing
Get-ChildItem -path C:\temp\images |
  Where-Object { $_.Length -ge 250Kb -and $_.lastwritetime -gt (get-date).addDays(-5) -and [Drawing.Image]::FromFile($_.FullName).Width -eq 1920 } | 
  move-item –PassThru | Rename-Item -NewName {-join @($_.Name,'.jpg')}

The problem is FromFile method is locking the file and preventing the move with this error message:

move-item : The process cannot access the file because it is being used by another process.

Upvotes: 0

Views: 2092

Answers (1)

Alicia
Alicia

Reputation: 328

You need to find the other process using the file, with for instance:

$lockedFile = "path/to/locked/file"
$lockingProcessID = Get-Process | foreach {$processVar = $_;$_.Modules `
    | foreach {if($_.FileName -eq $lockedFile) {$processVar.id}}}

and then kill the process:

Stop-Process -ID $lockingProcessID -Force

then try again to move your file.

Upvotes: 3

Related Questions