Powershell test-path then remove-item but file in use by another process
<p>I'm using Powershell for some file manipulation and performing the following steps:</p>

<ol>
<li>Copy a file from one location to another (copy-item)</li>
<li>Verify that the new file is where it's expected (test-path)</li>
<li>If verified in the new location, remove the original (remove-item)</li>
</ol>

<p>This process works 99.9% of the time but sometimes I'm receiving an error when the remove-item step occurs informing me that the original file is already in use / locked.  I can only assume that the process using this is the copy-item / test-path from steps 1 or 2.</p>

<p>Do I need to instruct Powershell to wait until the copy-item / test-path are finished before proceeding with the remove-item?  Or is it more likely that there is another process running somewhere else such as on access AV that is causing this problem?  If so, is there a method of easily retrying in the event of a file lock being in place?</p>

<p>Here is part of the code that performs the steps mentioned:</p>

<pre><code>if ($copySuccess = "TRUE") {
    $wiFiles = Get-ChildItem $xmlDir -Filter $itemNum*.*
    $wiFiles | ForEach-Object {
        if ($copySuccess -eq "TRUE") {
            Copy-Item -LiteralPath $xmlDir\$_ -Destination $processedDir
                if (!(Test-Path -LiteralPath $processedDir\$_)) {
                    $copySuccess = "FALSE"
                }
            } 
        }
    }                    
    if ($copySuccess -eq "TRUE") {
        Get-ChildItem $xmlDir -Filter $itemNum*.* | Remove-Item
    }
</code></pre>

<p>The files being moved are small text files or image files &lt;1MB and typically &lt;10 files per itemNum.</p>

<p>Thanks, Rob.</p>