2013-11-21 83 views
3

在PowerShell中,我相信我在觀察PowerShell在刪除內容之前試圖刪除文件夾。我正在使用的命令是Remove-Item刪除文件之前刪除項返回?

過去,與-recurse一起使用它會偶爾錯誤地抱怨目錄不是空的。當我看到那個錯誤時,當我去檢查時,我會發現目標目錄是空的。我最好的猜測是,它正在繼續,而文件仍在被刪除的過程中。現在我看到了更多的證據。

由於上述原因,我嘗試使用下面的代碼片段:

$toDelete = Get-ChildItem $path -Recurse 
[Array]::Reverse($toDelete) 
$toDelete | Remove-Item 
Remove-Item $path 

什麼,現在我得到的是以下提示:

Confirm 
The item at [path to directory] has children and the Recurse parameter was not specified. If you continue, all 
children will be removed with the item. Are you sure you want to continue? 
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): 

此外,該目錄是空的時我去檢查一下。我最好的猜測是$toDelete | Remove-Item在文件被實際刪除之前正在返回,並且我在Remove-Item $path上看到了此提示。

這是一個已知的問題?我懷疑發生了什麼問題嗎?我該如何解決它?

我試過使用cmd /C "rd /S [path to directory]",但是這是有問題的,因爲我發現退出代碼是0,因爲當它刪除一些正在使用的孩子時失敗。 (這是我的使用潛在的情況,我需要它是一個錯誤的情況。)

回答

2

帶-Recurse開關的Remove-Item在V1-V3中有問題(它實際上告訴你它不能正常工作在幫助中)。 它最終在V4中得到修復。我已經使用這種方法作爲解決方法,它總是對我有效:

$toDelete = Get-ChildItem $path -Recurse | 
select -expand property fullname | 
sort -length descending | 
Remove-Item 
Remove-Item $path 
+0

是的,我在幫助中看到。該幫助明確指出,它與'-Include'和'-Recurse'之間的相互作用有關,不過我並沒有這樣做。有趣。您將輸出捕獲到一個變量中。想想看,我認爲我抓住了一些其他的東西,以防止劇本在命令完成之前繼續前進。我會嘗試一下並報告。 – jpmc26

+0

我不認爲這實際上是在V4中修復的。我仍然看到問題。 – jpmc26