PowerShell はファイルサイズを KB、MB、GB で表示します 質問する

PowerShell はファイルサイズを KB、MB、GB で表示します 質問する

指定されたディレクトリのファイル サイズを取得する PowerShell スクリプトのセクションがあります。

さまざまな測定単位の値を変数に取得することはできますが、適切な値を表示する良い方法がわかりません。

$DirSize = "{0:N2}" -f (($DirArray | Measure-Object -property length -sum).sum)
$DirSizeKB = "{0:N2}" -f (($DirArray | Measure-Object -property length -sum).sum / 1KB)
$DirSizeMB = "{0:N2}" -f (($DirArray | Measure-Object -property length -sum).sum / 1MB)
$DirSizeGB = "{0:N2}" -f (($DirArray | Measure-Object -property length -sum).sum / 1GB)

バイト数が 1 KB 以上の場合は KB 値を表示します。KB 数が 1 MB 以上の場合は MB 値を表示します。

これを実現する良い方法はありますか?

ベストアンサー1

これを行う方法はたくさんあります。その 1 つを次に示します。

switch -Regex ([math]::truncate([math]::log($bytecount,1024))) {

    '^0' {"$bytecount Bytes"}

    '^1' {"{0:n2} KB" -f ($bytecount / 1KB)}

    '^2' {"{0:n2} MB" -f ($bytecount / 1MB)}

    '^3' {"{0:n2} GB" -f ($bytecount / 1GB)}

    '^4' {"{0:n2} TB" -f ($bytecount / 1TB)}

     Default {"{0:n2} PB" -f ($bytecount / 1pb)}
}

おすすめ記事