Powershell、GCI 出问题了?非空文件夹大小 returns 0

Powershell, GCI bugging out? Non-empty Folder size returns 0

我编写了一个 powershell 脚本,通过使用 gci 函数递归地添加找到的每个文件的文件大小来计算父目录中子文件夹的大小。

这适用于大多数文件夹,但以下文件夹除外: "\Fall Out Boy - A Little Less Sixteen Candles, A Little More [Touch Me]"

变量 $curfoldersize 应该给出 23089406 (22mb) 的值,但是函数 Get-FolderSize returns 0 而不是。由于某种原因,代码只在此文件夹上中断,其他文件夹名称似乎工作正常。我不确定是什么导致了这里的错误。

文件夹内容:

# Parent Directory to find folders
$dirpath = "H:\Parent Dir\"
$logpath = "$PSScriptRoot\Logs\"
$logpath = -join($logpath, ($dirpath|split-path -leaf), ".txt")

# Maximum size of each folder (empty or non-empty)
$foldermaxsize = 19 # <- max size of each folder (e.g. 10 * 1MB = 10MB, 10 * 1KB = 10KB, etc)
$sizeunit = 1MB # <- size denominator (e.g. 1KB, 1MB, 1GB, etc)

$foldermaxsize = $foldermaxsize * $sizeunit


# returns size of single folder by summing all items (recursive) inside
Function Get-FolderSize {
    # allows cmd options 
    [cmdletbinding()]
    Param ( 
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline = $true)]
        $folderpath
    )
    $size = 0
    # calculate folder size and recurse as needed
    Foreach ($file in $(gci $folderpath -recurse -Force)){
     If (-not ($file.psiscontainer)) {
        $size += $file.length
        }
    }

    # return the value and go back to caller
    return $size
}


# Array containing filepaths of each directory (recursive) found within $dirpath
# gci = GetChildItem
$Folders = @(gci $dirpath -Recurse | ?{ $_.PSIsContainer } |  Select-Object -ExpandProperty FullName) 

# Check for null results from cgi function
if ($Folders.length -eq 0) {
  write-host "   no folders." 
} else {
    # $folder = full path of current folder
    ForEach ($folder in $Folders){
        # returns int size of Folder (by recursively summing all child filesize)
        $curfoldersize = Get-FolderSize $folder 
        Write-Output $curfoldersize
    }



if ($Host.Name -eq "ConsoleHost")
{
    Write-Host "Press any key to continue..."
    $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}

}

在此表达式中(foreach 函数中的循环源):

gci $folderpath -recurse -Force

$folderpath 未显式绑定到任何命名参数,PowerShell 将其隐式绑定到 -Path.

来自 the Get-ChildItem parameter documentation(强调已添加):

-Path

Specifies a path to one or more locations. Wildcards are accepted. The default location is the current directory (.).

[Touch Me] 恰好是描述一个字符的通配符转义序列,其值为 Touch Me.

要禁止通配符扩展,请改为将参数绑定到 -LiteralPath 参数:

gci -LiteralPath $folderpath -recurse -Force

-LiteralPath

Specifies a path to one or more locations. The value of LiteralPath is used exactly as it's typed. No characters are interpreted as wildcards.