Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
    
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
add comment

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

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

1 Answer

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)

    try
    {
        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)

        $fileStream.Close()

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

        $true        
    }
    catch
    {
        Write-Host "Test-LockedFile found a locked file (i.e. `$false)"
        $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"
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.