PowerShell 将文件大小显示为 KB、MB 或 GB

问题描述 投票:0回答:8

我有一个 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 等。

有什么好的方法可以实现这一点吗?

batch-file powershell scripting
8个回答
22
投票

有很多方法可以做到这一点。这是一个:

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

21
投票

我的与 @zdan 的类似,但写成脚本函数:

function DisplayInBytes($num) 
{
    $suffix = "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
    $index = 0
    while ($num -gt 1kb) 
    {
        $num = $num / 1kb
        $index++
    } 

    "{0:N1} {1}" -f $num, $suffix[$index]
}

19
投票

我希望下面的代码能帮助你...

$file = 'C:\file.txt'
Write-Host((Get-Item $file).length/1KB) // returns file length in KB
Write-Host((Get-Item $file).length/1MB) // returns file length in MB
Write-Host((Get-Item $file).length/1GB) // returns file length in GB

10
投票

这是我不久前编写的一个函数,它利用 Win32 API 来完成您正在寻找的任务。

Function Convert-Size {
    <#
        .SYSNOPSIS
            Converts a size in bytes to its upper most value.

        .DESCRIPTION
            Converts a size in bytes to its upper most value.

        .PARAMETER Size
            The size in bytes to convert

        .NOTES
            Author: Boe Prox
            Date Created: 22AUG2012

        .EXAMPLE
        Convert-Size -Size 568956
        555 KB

        Description
        -----------
        Converts the byte value 568956 to upper most value of 555 KB

        .EXAMPLE
        Get-ChildItem  | ? {! $_.PSIsContainer} | Select -First 5 | Select Name, @{L='Size';E={$_ | Convert-Size}}
        Name                                                           Size                                                          
        ----                                                           ----                                                          
        Data1.cap                                                      14.4 MB                                                       
        Data2.cap                                                      12.5 MB                                                       
        Image.iso                                                      5.72 GB                                                       
        Index.txt                                                      23.9 KB                                                       
        SomeSite.lnk                                                   1.52 KB     
        SomeFile.ini                                                   152 bytes   

        Description
        -----------
        Used with Get-ChildItem and custom formatting with Select-Object to list the uppermost size.          
    #>
    [cmdletbinding()]
    Param (
        [parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [Alias("Length")]
        [int64]$Size
    )
    Begin {
        If (-Not $ConvertSize) {
            Write-Verbose ("Creating signature from Win32API")
            $Signature =  @"
                 [DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
                 public static extern long StrFormatByteSize( long fileSize, System.Text.StringBuilder buffer, int bufferSize );
"@
            $Global:ConvertSize = Add-Type -Name SizeConverter -MemberDefinition $Signature -PassThru
        }
        Write-Verbose ("Building buffer for string")
        $stringBuilder = New-Object Text.StringBuilder 1024
    }
    Process {
        Write-Verbose ("Converting {0} to upper most size" -f $Size)
        $ConvertSize::StrFormatByteSize( $Size, $stringBuilder, $stringBuilder.Capacity ) | Out-Null
        $stringBuilder.ToString()
    }
}

7
投票

使用开关或一组“if”语句。你的逻辑(伪代码)应该如下所示:

  1. 大小至少为 1 GB 吗?是的,以 GB 显示(否则...)
  2. 大小是否至少为 1 MB?是的,以MB显示(否则...)
  3. 以KB显示。

请注意,您应该按从最大尺寸到最小尺寸的相反顺序进行测试。是的,我本可以为您编写代码,但我怀疑您知道足够的知识,可以将上述内容转换为工作脚本。只是这个方法让你难住了。


1
投票

我在 Bill Stewart "d.ps1" 脚本中添加了函数 DisplayInBytes($num)

function DisplayInBytes($num)
{
    $suffix = "oct", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib"
    $index = 0
    while ($num -gt 1kb) 
    {
        $num = $num / 1kb
        $index++
    }

    $sFmt="{0:N"
    if ($index -eq 0) {$sFmt += "0"} else {$sFmt += "1"}
    $sFmt += "} {1}"
    $sFmt -f $num, $suffix[$index]
}

更换块

  # Create the formatted string expression.
   $formatStr = "`"{0,5} {1,10} {2,5} {3,15:N0} ({4,11})"   $formatStr += iif { -not $Q } { " {5}" } { " {5,-22} {6}" }   $formatStr += "`" -f `$_.Mode," +
        "`$_.$TimeField.ToString('d')," +
        "`$_.$TimeField.ToString('t')," +
        "`$_.Length,`$sfSize"

还有

  if (-not $Bare) {
    $sfSize=DisplayInBytes $_.Length
    invoke-expression $formatStr

最后

  # Output footer information when not using -bare.
  if (-not $Bare) {
    if (($fileCount -gt 0) -or ($dirCount -gt 0)) {
      $sfSize = DisplayInBytes $sizeTotal
      "{0,14:N0} file(s) {1,15:N0} ({3,11})`n{2,15:N0} dir(s)" -f
        $fileCount,$sizeTotal,$dirCount,$sfSize
    }
  }

0
投票

一堆 if/switch 的替代方法是使用 while 循环,直到您的值达到正确的大小。它可以扩展!

[double] $val = ($DirArray | Measure-Object -property length -sum).sum
while($val -gt 1kb){$val /= 1kb;}
"{0:N2}" -f $val

0
投票

如果您有 WSL,那么您可以直接从 PWSH 调用它:

wsl ls -lh

如果你使用 exa 就更好了:

wsl exa -l /mnt/c

一个缺点是制表符补全会给你

.\folder1\folder2
,它不能与
exa
一起使用,所以我编写了一个自定义函数来替换斜杠:

Function ll { 
  $target = '.' #default to current directory is no command-line arguments supplied
  if($args[0]){
    $target = $args[0] -replace "`\\","`/"
  }
  wsl exa -l --group --icons --sort=modified $target 
}

!!!通过

$PROFILE
将上面的内容放入您的
notepad.exe $PROFILE
文件中,并使用
. $PROFILE
重新加载 pwsh。

现在

ll
将很好地显示信息,制表符补全将适用于子目录,例如

ll .\subDir\subSubDir.

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.