I'm in need to get a file listing from a directory which mustn't include incomplete files (i.E. Files, which are currently copied to the directory)

How can i get the Get-ChildItem to exclude incomplete files?

migrated from stackoverflow.com Feb 28 '13 at 15:10

This question came from our site for professional and enthusiast programmers.

  • I don;'t think there is an easy way to do this. Have you tried checking modified date? – JNK Feb 28 '13 at 13:33
  • Hmm... Good Point. Maybe i could build a workaround to only touch files, which "modified date" is >1min... – Julian Wittler Feb 28 '13 at 13:47
  • There is no way for another program to know whether a file is "complete". The closest you can possibly get is whether the file is currently opened by another process, and I don't think it would be easy in Powershell, without going deep into native Win32 functions. – grawity Feb 28 '13 at 15:26

You might be able to create a a "test" function that tries to get an exclusive lock against the file that you intend to copy. If the exclusive lock succeeds that would imply that the file was not still being copied. Within PowerShell you have access to the .Net Framework library classes, which in this case can be found in the System.IO library. A possible sample script is below. Copy it to your C:\Temp directory and create a few text files. Open one or more of the text files with Microsoft Word or some program which is going to lock the file (Notepad won't). You would expect the output to be all the files that were not locked.

function Test-UnLockedFile
    param([string] $fileNameAndPath)

        Write-Host "Test-LockedFile called with $fileNameAndPath"

        $fileInfo = New-Object ('System.IO.FileInfo') "$fileNameAndPath"

        $fileStream = $fileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)


        Write-Host "Test-LockedFile found an unlocked file (i.e. `$true)"

        Write-Host "Test-LockedFile found a locked file (i.e. `$false)"

$files = Get-ChildItem -Path "C:\Temp\" -Exclude *.ps1

$unlockedFiles = $files | Where-Object { Test-UnLockedFile $_.FullName }

foreach ($file in $unlockedFiles)
    $name = $file.FullName
    Write-Host "Found unlocked file at $name"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy