Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"[" and "]" characters mess up get-childitem

Using PowerShell 4.0, I am trying to get the size of multiple directories and I am getting very inconsistent results between what windows tells me and what my code is telling me.

The code in question is:

$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

if $folderInfo.rootFolder = D:\sample then I get what I want but if $folderInfo.rootFolder = D:\[sample then I get

Get-ChildItem : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: 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

The same holds true if D:\sample contains a folder somewhere in it's children that is "[sample". I will get correct results from everything else, but anything in or beyond the problem directory. Both $dir.pspath and $dir.fullname screw things up.

Edit: changed the above code to reflect it's current state and included the full error.
edit again: The code above now has some debugging temp variables.

like image 732
LuckyFalkor84 Avatar asked Feb 06 '14 21:02

LuckyFalkor84


1 Answers

Use the -LiteralPath parameter in place of -Path to suppress the wildcard globbing. Also, since you're using V4, you can use the -Directory switch and dispense with the $_.iscontainer filter:

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

If you have more squre brackets farther down the directory tree, keep using literpath in subsequent Get-ChildItem commands:

$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
like image 107
mjolinor Avatar answered Oct 22 '22 02:10

mjolinor