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

时间:2019-03-08 16:55:30

标签: powershell filesize

我目前正在使用Powershell脚本将随机选择的歌曲从NAS复制到SD卡上。更为复杂的是,每个文件夹最多只能包含512首歌曲,而且很显然,在卡上的可用空间用完之前,必须先停止该过程。

我已经编写了几乎完整的脚本(用于测试目的的歌曲数量减少了),但是在跟踪已复制文件的总大小方面很费劲。例如,一个总共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

1 个答案:

答案 0 :(得分:0)

这是一种使用其他类似于Powershell的模式来解决您的问题的方法。它将当前要复制的文件与剩余空间进行比较,如果满足该条件,它将退出顶级循环。

#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
    }
}