0

Is Get-ChildItem able to filter out the files which are in locked state? Such as logs files currently in use by application and Get-ChildItem should skip on these files in results.

Example:

Get-ChildItem -Path C:\Logs\* # Maybe do pipelines condition here for filtering out locked files
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Yong Cai
  • 143
  • 1
  • 17

1 Answers1

1

I don't think this can be done using a Filter and of course you should keep in mind that files can get locked/unlocked anytime, so this would always be just snapshot that can change almost instantly.
This may be a way to do it:

Get-ChildItem -Path D:\Logs -File | ForEach-Object {
    try {
        $stream = $_.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
        if ($stream) { $stream.Close() }
        Write-Host "File $($_.FullName) is currently not locked" -ForegroundColor Green
    } 
    catch {
        Write-Host "File $($_.FullName) is currently locked" -ForegroundColor Red
        # emit the locked fileInfo object?
        $_
    }
}
Theo
  • 57,719
  • 8
  • 24
  • 41