选项 -recurse 有时不适用于 PowerShell cmdlet get-childitem [英] Option -recurse sometimes does not work for PowerShell cmdlet get-childitem
问题描述
假设我有这个文件:
C:\[foo]\bar
然后我运行这些 PowerShell 命令:
I then run these PowerShell commands:
$path = 'C:\[foo]'
get-childitem -literalpath $path
一切正常,get-childitem
显示文件 bar
,然后立即返回.
Everything works fine, get-childitem
shows me the file bar
, then returns immediately.
现在我添加 -recurse
选项:
$path = 'C:\[foo]'
get-childitem -literalpath $path -recurse
get-childitem
不再显示文件 bar
.此外,该 cmdlet 运行时间很长,并且会为 C:\Windows
下的文件夹显示各种权限被拒绝"错误消息,这显然是因为它扫描了整个 C: 驱动器.
get-childitem
no longer displays the file bar
. In addition, the cmdlet runs a long time and displays various "permission denied" error messages for folders underneath C:\Windows
, apparently because it scans the entire C: drive.
问题与文件夹 [bar]
的名称中有括号有关.如果我将文件夹重命名为 bar
,即没有括号,递归的结果会按预期工作.
The problem is tied to the fact that the folder [bar]
has brackets in the name. If I rename the folder to bar
, i.e. without brackets, the result with recursion works as expected.
我的主要问题:如何说服 get-childitem
递归扫描名称中包含括号(或其他特殊字符)的文件夹?
My main question: How can I convince get-childitem
to recursively scan folders that have brackets (or other special characters) in the name?
第二个问题:这是一个已知的错误吗?
A secondary question: Is this a known bug?
环境:Windows 8.1、PowerShell 4.0.
Environment: Windows 8.1, PowerShell 4.0.
我验证了在 PowerShell 2.0(在 Windows 7 机器上)get-childitem
返回相同的结果,无论是否使用 -recurse
.该行为似乎在 3.0 或 4.0 版中发生了变化.
I verified that in PowerShell 2.0 (on a Windows 7 machine) get-childitem
returns the same result with or without -recurse
. It appears that the behaviour has changed either in version 3.0 or 4.0.
推荐答案
我在使用 PowerShell 4.0 的 Windows 7 x64 位上也得到与您相同的结果.从它的外观来看,递归功能忽略了 -LiteralPath
.
I also get the same results as you on Windows 7 x64 bit with PowerShell 4.0. From the looks of it the recursive functionality is ignoring the -LiteralPath
.
这是一种解决方法,我发现了一个 TechNet 帖子 讨论了同样的问题.那篇文章中的 OP 最终使用 -Path
并双重转义括号.
This is a workaround put I found a TechNet post discussing the same issue. The OP in that post ended up using -Path
and double escaping the brackets.
$path = "C:\[foo]"
$escapedPath = $path.Replace("[","``[").Replace("]","``]")
Get-ChildItem -Path $escapedPath -Recurse
注意:如果删除 -Recurse
Get-ChildItem : Cannot find path 'C:\`[foo`]' because it does not exist.
这篇关于选项 -recurse 有时不适用于 PowerShell cmdlet get-childitem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!