【问题标题】:Move-Item causes "File Already Exists" error, despite folder having been deleted尽管文件夹已被删除,Move-Item 仍会导致“文件已存在”错误
【发布时间】:2017-09-18 18:16:05
【问题描述】:

我有一些代码可以删除一个文件夹,然后将文件从临时目录复制到该文件夹​​所在的位置。

Remove-Item -Path '.\index.html' -Force
Remove-Item -Path '.\generated' -Force -Recurse  #folder containing generated files

#Start-Sleep -Seconds 10 #uncommenting this line fixes the issue

#$tempDir contains index.html and a sub folder, "generated", which contains additional files.  
#i.e. we're replacing the content we just deleted with new versions.
Get-ChildItem -Path $tempDir | %{
    Move-Item -Path $_.FullName -Destination $RelativePath -Force 
}

我收到一个间歇性错误,Move-Item : Cannot create a file when that file already exists. 在 generated 路径的 Move-Item 行上。

我已经能够通过在第二个 Remove-Item 语句之后添加一个 hacky Start-Sleep -Seconds 10 来防止这种情况;虽然这不是一个很好的解决方案。

我认为问题在于 Remove-Item 语句完成/代码移至下一行,在操作系统赶上实际文件删除之前;虽然这看起来很奇怪/令人担忧。注意:生成的文件夹中有大约 2,500 个文件(全部在 1-100 KB 之间)。

没有其他进程访问这些文件夹(即我什至关闭了我的资源管理器窗口并测试了这个目录从我的 AV 中排除)。

我考虑过其他选择:

  • 使用Copy-Item 代替Move-Item。我不喜欢这样,因为它需要在不需要时创建新文件(即副本比移动慢)......它比我目前的睡眠黑客要快;但仍然不理想。

  • 删除文件而不是文件夹,然后遍历子文件夹并将文件复制到新位置。这会起作用,但是对于应该很简单的事情来说,代码要多得多;所以我不想追求那个选择。

  • Robocopy 可以解决问题;但我更喜欢纯 PowerShell 解决方案。如果没有干净的解决方案,这是我最终会选择的选项。

问题

  • 以前有人见过吗?
  • 这是一个错误,还是我错过了什么?
  • 有人知道修复/好的解决方法吗?

更新

在单独的作业中运行删除(即使用下面的代码)没有解决问题。

Start-Job -ScriptBlock {
    Remove-Item -Path '.\index.html' -Force
    Remove-Item -Path '.\generated' -Force -Recurse  #folder containing generated files
} | Wait-Job | Out-Null

#$tempDir contains index.html and a sub folder, "generated", which contains additional files.  
#i.e. we're replacing the content we just deleted with new versions.
Get-ChildItem -Path $tempDir | %{
    Move-Item -Path $_.FullName -Destination $RelativePath -Force 
}

更新 #2

添加此作品;即我们不是等待固定时间,而是等待每秒删除/检查路径。如果它在 30 秒后没有被移除,我们认为它不会被移除;所以不管怎样都继续(这将导致move-item 抛出一个在其他地方处理的错误)。

# ... remove-item code ...
Start-Job -ScriptBlock {
    param($Path)
    while(Test-Path $Path){start-sleep -Seconds 1}
} -ArgumentList '.\generated' | Wait-Job -Timeout 30 | Out-Null
# ... move-item code ...

【问题讨论】:

  • 您是否考虑将删除作为单独的作业运行?我不知道在自己的内存空间中运行的开销是否会因为所花费的时间而“解决”问题,或者是否真的会等到文件被删除。
  • @Matt:我很乐意在单独的作业下运行它,只要我可以在该作业完成后排队移动项目(即start-job ... | wait-job | out-null; move-item ...)......现在将测试看看这是否有帮助......
  • @Matt:遗憾的是,这种方法并不令人高兴(有关我使用的代码,请参阅修改后的问题)。
  • @Matt:附言。我用你的建议来调整我的睡眠声明;即利用wait-job 上的超时选项等待最长时间;而否则每秒检查文件夹并在它消失的那一刻继续......仍然非常hacky所以我会留下这个问题;但它确实有效。
  • 这可能是一个很好的解决方案。我也会运行Remove-Job * -force,否则那些挂起的工作只会坐在那里。

标签: file powershell directory windows-7-x64 powershell-5.0


【解决方案1】:

最后我选择了这个解决方案;不完美,但它有效。

Remove-Item -Path '.\index.html' -Force
Remove-Item -Path '.\generated' -Force -Recurse  #folder containing generated files

#wait until the .\generated directory is full removed; or until ~30 seconds has elapsed
1..30 | %{
    if (-not (Test-Path -Path '.\generated' -PathType Container)) {break;}
    Start-Sleep -Seconds 1
}

Get-ChildItem -Path $tempDir | %{
    Move-Item -Path $_.FullName -Destination $RelativePath -Force 
}

这与问题更新 #2 中的工作相同;只是不需要工作的开销;只是循环直到文件被删除。

这是包装为可重用 cmdlet 的上述逻辑:

function Wait-Item {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline, HelpMessage = 'The path of the item you wish to wait for')]
        [string]$Path
        ,
        [Parameter(HelpMessage = 'How many seconds to wait for the item before giving up')]
        [ValidateRange(1,[int]::MaxValue)]
        [int]$TimeoutSeconds = 30
        ,
        [Parameter(HelpMessage = 'By default the function waits for an item to appear.  Adding this switch causes us to wait for the item to be removed.')]
        [switch]$Remove
    )
    process {
        [bool]$timedOut = $true
        1..$TimeoutSeconds | %{
            if ((Test-Path -Path $Path) -ne ($Remove.IsPresent)){$timedOut=$false; return;}
            Start-Sleep -Seconds 1
        }
        if($timedOut) {
            Write-Error "Wait-Item timed out after $TimeoutSeconds waiting for item '$Path'"
        }
    }
}

#example usage:
Wait-Item -Path '.\generated' -TimeoutSeconds 30 -Remove

【讨论】:

  • 我不确定它是如何工作的。 break 中断循环 % 是 Foreach-Object 的简写,它不是循环而是 cmdlet。因此,break 语句将在外部范围内打破 something else,这可能是完全出乎意料的。
猜你喜欢
  • 2020-11-20
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 2017-08-04
相关资源
最近更新 更多