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

问题描述 投票:1回答:1

我目前正在开发一个powershell脚本,将随机选择的歌曲从我的NAS复制到SD卡上。作为一个额外的复杂功能,我每个文件夹不超过512首歌曲,显然,需要在卡片上的可用空间用完之前停止这个过程。

我已经写了一个几乎完整的脚本(用于测试目的的歌曲数量减少),但我正在努力跟踪我复制的文件的总大小。例如,一个总共112MB文件的测试运行给出的记录值($ copy_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 filesize
1个回答
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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.