Powershell 添加文件大小,意外结果

Powershell adding file sizes, unexpected result

我目前正在编写一个 powershell 脚本,用于将随机选择的歌曲从我的 NAS 复制到 SD 卡上。作为一个额外的并发症,我每个文件夹不能超过 512 首歌曲,而且显然,我需要在我 运行 用完卡上的免费 space 之前停止该过程。

我已经编写了一个几乎完整的脚本(出于测试目的减少了歌曲数量),但我正在努力跟踪我复制的文件的总大小。例如,一个测试 运行 总共有 112MB 的文件给出了一个记录值(在 $copied_size 中)1245。我不知道那个值是什么意思,它似乎没有是 GB、Gb、MB 或 Mb 的实际值。我显然在这里遗漏了一些东西。有什么想法吗?

这是脚本,我还没有设置大小限制:

$j = 1
$i = 0
$files_per_folder = 5
$sd_card_size = 15920000000
$copied_size = 0
$my_path = '\WDMYCLOUD\Public\Shared Music'
$random = Get-Random -Count 100 -InputObject (1..200)
For ($j=1; $j -le 5; $j++)
{
    md ("F:\" + $j)
    $list = Get-ChildItem -Path $my_path | ?{$_.PSIsContainer -eq $false -and $_.Extension -eq '.mp3'}
    For ($i=0; $i -le $files_per_folder - 1; $i++)
    {
        Copy-Item -Path ($my_path + "\" + $list[$random[(($J - 1) * $files_per_folder) +$i]]) -Destination ('F:\' + $j)
        $copied_size = $copied_size + ($my_path + "\" + $list[$random[(($J - 1) * $files_per_folder) +$i]]).length
    }
}
Write-Host "Copied Size =  " $copied_size

这里有一种方法 可以使用一些更类似于 powershell 的模式来解决您的问题。它将当前要复制的文件与剩余的 space 进行比较,如果该条件为真,将退出顶层循环。

#requires -Version 3

$path = '\share\Public\Shared Music'
$filesPerFolder = 5
$copySize = 0
$random = 1..200 | Get-Random -Count 100

$files = Get-ChildItem -Path $path -File -Filter *.mp3

:main
for ($i = 1; $i -le 5; $i++) {
    $dest = New-Item -Path F:$i -ItemType Directory -Force

    for ($j = 0; $j -le $filesPerFolder; $j++) {
        $file = $files[$random[(($j - 1) * $filesPerFolder) + $i]]
        if ((Get-PSDrive -Name F).Free -lt $file.Length) {
            break main
        }

        $file | Copy-Item -Destination $dest\
        $copySize += $file.Length
    }
}