"["和"]"字符混乱了get-childitem命令的结果。"

9

使用PowerShell 4.0,我尝试获取多个目录的大小,但是我得到的结果与Windows告诉我的结果非常不一致。

相关代码如下:

$temp4 = ($folderInfo.rootFolder).fullname
$folderInfo.directories += Get-ChildItem -LiteralPath $temp4 -Recurse -Force -Directory
$folderInfo.directories += $folderInfo.rootFolder
foreach ($dir in $folderInfo.directories)
{
    $temp3 = $dir.fullname
    $temp2 = Get-ChildItem -LiteralPath $temp3 -Force
    $temp = (Get-ChildItem -LiteralPath $dir.fullname -Force -File | Measure-Object -Property length -Sum -ErrorAction SilentlyContinue).Sum
    $folderInfo.totalSize += $temp
}
return $folderInfo

如果$folderInfo.rootFolder = D:\sample,那么我可以得到我想要的结果;但是如果$folderInfo.rootFolder = D:\[sample,那么我会得到以下错误:

Get-ChildItem: 无法检索cmdlet的动态参数。指定的通配符字符模式无效:sample [sample
At C:\powershell scripts\test.ps1:55 char:12
+ $temp = (Get-ChildItem $dir.fullname -Force -File | Measure-Object -Property l ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem],ParameterBindingException
+ FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.GetChildItemCommand

如果D:\sample包含一个名为"[sample"的子目录,那么同样会出现以上问题。除此之外的任何其他目录都能得到正确的结果。无论是$dir.pspath还是$dir.fullname都会导致问题。
编辑:更改上述代码以反映其当前状态,并包括完整的错误信息。
再次编辑:上述代码现已添加了一些调试临时变量。
1个回答

18

使用-LiteralPath参数代替-Path参数以禁止通配符匹配。 此外,由于您使用的是V4版本,因此可以使用-Directory开关,并且不需要$_.iscontainer过滤器:

$folderInfo.directories = 
 Get-ChildItem -LiteralPath $folderInfo.rootFolder -Recurse -Force -Directory 

如果在目录树的较深处有更多的方括号,请在后续的Get-ChildItem命令中继续使用literalpath。
$folderInfo.directories += Get-ChildItem -LiteralPath $folderInfo.rootFolder -Recurse -Force -Directory
    $folderInfo.directories += Get-Item -LiteralPath $folderInfo.rootFolder
    foreach ($dir in $folderInfo.directories)
    {
        $temp2 = Get-ChildItem -LiteralPath $dir.PSPath -Force
        $temp = (Get-ChildItem -LiteralPath $dir.fullname -Force -File | Measure-Object -Property length -Sum -ErrorAction SilentlyContinue).Sum
        $folderInfo.totalSize += $temp
    }
    return $folderInfo

1
我根据你的建议修改了代码,但仍然出现错误。 - LuckyFalkor84
编辑问题并发布更新后的代码和精确的错误信息。 - mjolinor
修改了我的原始答案。 - mjolinor
据我所知,无论是否使用-literalpath参数,get-childitem命令都可以工作,只要我提供的字符串中没有"["。然而奇怪的是,literalPath参数在foreach循环中能够如预期地起作用。 - LuckyFalkor84
1
我再次修改了上面的代码。 不过很快我就找到了罪魁祸首。 -recurse参数会查找通配符,而不管literalPath。 这是基于递归参数提供的详细信息所假定的。 - LuckyFalkor84
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接