2017-02-09 45 views
1

我有一個腳本,我遞歸刪除某些目錄中的一些文件。問題在於該目錄的規範。Get-Childitem目錄通配符「訪問被拒絕」

當我嘗試顯式指定它(即只清除user1的目錄),它工作正常:

$temp = "C:\Users\user1\AppData\Local\Temp\" 
Get-ChildItem $temp -Recurse -Force -Verbose -ErrorAction SilentlyContinue | remove-item -force -Verbose -recurse -ErrorVariable FailedItems -ErrorAction SilentlyContinue 

然而,當我用通配符指定它(即影響這臺電腦上的所有用戶)

$temp = "C:\Users\*\AppData\Local\Temp\*" 
Get-ChildItem $temp -Recurse -Force -Verbose -ErrorAction SilentlyContinue | remove-item -force -Verbose -recurse -ErrorVariable FailedItems -ErrorAction SilentlyContinue 

它失敗,出現錯誤

Get-ChildItem : Access is denied 
At line:7 char:1 
+ Get-ChildItem $localTempDir -Recurse -Force -Verbose -ErrorAction Sil ... 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
+ CategoryInfo   : NotSpecified: (:) [Get-ChildItem], UnauthorizedAccessException 
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetChildItemCommand 

這怎麼可能? 這絕對不是權限問題,因爲它的相同目錄。 是的,我用提升的權限運行腳本。
以這種格式指定的其他目錄,例如

C:\Users\*\AppData\Local\Microsoft\Windows\Caches 
C:\Windows\Temp\* 

被清除爲魅力。

+0

喜,這不能與特殊/隱藏/系統配置文件夾相關嗎?例如'默認' – sodawillow

+0

也許吧。如何診斷? – Suncatcher

+0

枚舉配置文件,排除特殊配置文件,應用其餘的邏輯? – sodawillow

回答

1

也許你可以使用的東西沿着這些線路,如果要排除配置文件列表,並處理子文件夾列表:

$targets = "AppData\Local\Microsoft\Windows\Caches", 
      "AppData\Local\Microsoft\Windows\Temporary Internet Files" 

$special = @("Default", "Public") 

$profiles = Get-ChildItem "C:\Users" -Directory | 
    Where-Object Name -NotIn $special | 
    Select-Object -ExpandProperty FullName 

$profiles | ForEach-Object { 
    foreach($target in $targets) { 
     $path = Join-Path $_ $target 
     #delete/empty $path 
    } 
} 

注:語法是PS3.0 +

+0

好吧,它的工作原理沒有錯誤,但是如果我從'$ special'腳本中刪除'Public',它也會影響它。但是,如果我刪除'Default',它的垃圾無論如何都不會被刪除。爲什麼?腳本是否僅處理非隱藏(非系統)目錄?默認文件夾也可以包含很多臨時文件,因此應該進行處理。 – Suncatcher

+0

我覺得'-Force'可以幫助'gci' – sodawillow

+0

正確!完全按預期工作。 – Suncatcher