Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

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:empimages |
  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...