Monday, 11 July 2016

Powershell script to move files when a file is not open by another process.

Recently I wrote a powershell script which was required to move any file found in a directory and move it into another directory (the script is called by a Control-M cyclic job that run every 5 mins to transfer files to/from a manage file transfer utility) One of the considerations with this is to ensure that the files being moved are not open or being written to when attempting to move them. I also found I needed to handle the case where the destination already contained a file with the same name, and that file was open. Move-Item with the -force flag is not enough as this will fail if the file is open for editing.

How to do this - you need to test to see if the file is open by another process. The following code fragment is an example of this:

foreach ($fileName in $inPath)
{
    if(Test-Path $fileName)
    {
        try { [IO.File]::OpenWrite($fileName).close() }
        catch 
        { 
            Write-Host "the file is open" 
            continue
        }
     }
     Move-Item $fileName $destination -force
}   

So what is happening here is that the script is iterating through each file in the input directory. It then tests to see if the file can be read by the current process. Next, the script will try to open the file for editing - if this fails the current iteration of the loop will be exited, else the file will be moved.

This example is only testing for the file existing and being open in the destination folder - you also need  to test to see if the file in the input location is being written to... the code for which is basically the same.

EDIT: For a DOS version, go to this post

No comments:

Post a Comment