【问题标题】:Get-Childitem directory wildcard "Access is denied"Get-Childitem 目录通配符“访问被拒绝”
【发布时间】:2017-06-28 01:10:31
【问题描述】:

我有一个脚本,可以递归地删除某个目录中的一些文件。问题在于该目录的规范。

当我尝试明确指定它(即仅清除 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

但是,当我使用通配符指定它时(即影响此 PC 上的所有用户)

$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\*

像魅力一样被净化。

【问题讨论】:

  • 嗨,这不能与特殊/隐藏/系统配置文件文件夹有关吗?例如Default
  • 也许吧。如何诊断?
  • 枚举配置文件,排除特殊配置文件,应用其余逻辑?

标签: powershell directory permissions cmdlet


【解决方案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+

【讨论】:

  • 好吧,它可以正常工作,但是如果我从 $special 脚本中删除 Public 也会影响它。但是如果我删除Default,它的垃圾无论如何都不会被删除。为什么?脚本是否只处理非隐藏(非系统)目录?默认文件夹也可以包含许多临时文件,因此应该进行处理。
  • 我认为-Force 可以在这里帮助gci
  • 正确!完全按预期工作。
  • 但是,我仍然不清楚我的通配符形式 C:\Users\*\AppData\Local\Temp\* 有什么问题。为什么gci 在这里失败了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 2010-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
相关资源
最近更新 更多