How to use Get-ChildItem to filter out locked/being used by another process files?

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.


Get-ChildItem -Path C:\Logs\* # Maybe do pipelines condition here for filtering out locked files

1 answer

  • answered 2019-06-20 09:20 Theo

    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?