Quantcast
Viewing all articles
Browse latest Browse all 21975

Powershell is locking the file when I test for locked status

I've written a script that processes video files and then moves the original to another folder if they are not currently locked by another process. The function that I use to test for a file lock appears to to be locking the file. Can anyone give a suggestion on how to get powershell to release it's lock on the file so I can move the file?
--------------------
Here's the error-

Move-Item : The process cannot access the file because it is being used by another process.
At E:\Scripts\VideoMover\VideoMover.ps1:55 char:13
+             Move-Item $TempPath$item $CopyPath
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (E:\VD_Temp\rm10...2013_121426.asf:FileInfo) [Move-Item], IOException
    + FullyQualifiedErrorId : MoveFileInfoItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand

---------------------
And the script-

$TempPath = "E:\VD_Temp\"
$VideoBase = "E:\Video\"
$CopyBase = "E:\Copy\"

function TestLockStatus($filePath) {
    $fileInfo = New-Object System.IO.FileInfo $filePath
    
    try {
        $fileStream = $fileInfo.Open( [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read )
        #write-host $filePath "is NOT locked"
        return $false
    }
    catch {
        #write-host $filePath "IS locked"
        return $true
    }
}

$items = Get-ChildItem -Path "$TempPath" | Where-Object {$_.Extension -eq ".asf"}
foreach ($item in $items)
{
    # if the item is not a directory and it is NOT locked, then process it.
    $FileToTest = $TempPath+$item
    $FileStatus = (TestLockStatus($FileToTest))
    if (($item.Attributes -ne "Directory") -and ($FileStatus -eq $false)) {
        # Gather info from file name
        $Dept = $item.Name.Substring(7,2)
        $UserType = $item.Name.Substring(9,2)
        $UserNumber = $item.Name.Substring(11,2)
        $RoomNumber = $item.Name.Substring(0,6)

        $VideoPath = $VideoBase + $Dept + "\" + $Dept + $UserType + $UserNumber
        $MP4Path = $VideoPath + "\" + $item.name.Replace(".asf", ".mp4")

        if ((Test-Path $MP4Path) -ne $true) {
            $Prog = ".\ffmpeg.exe"
            $Args = "-n -i $TempPath$item -vcodec copy $MP4Path"
            Start-Process $Prog -ArgumentList $Args -Wait
        }

        $CopyPath = $CopyBase + $RoomNumber
        if ((Test-Path $CopyPath$item) -ne $true) {
            Move-Item $TempPath$item $CopyPath
        }
    }
}


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>