source

PowerShell 디스플레이 파일 크기(KB, MB 또는 GB)

nicesource 2023. 9. 1. 21:06
반응형

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)

바이트 수가 1KB 이상이면 KB 값을 표시합니다.KB 수가 1MB 이상이면 MB 등을 표시합니다.

이것을 달성할 수 있는 좋은 방법이 있습니까?

이렇게 하는 방법은 여러 가지가 있습니다.여기 하나 있습니다.

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

내 것은 @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]
}

다음 코드가 당신에게 도움이 되길 바랍니다...

$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

여기 당신이 원하는 것을 달성하기 위해 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()
    }
}

스위치 또는 "if" 문 집합을 사용합니다.논리(의사 코드)는 다음과 같아야 합니다.

  1. 크기가 1GB 이상입니까?예, GB 단위로 표시(기타...)
  2. 크기가 1MB 이상입니까?예, MB 단위로 표시합니다(기타...)
  3. KB 단위로 표시합니다.

가장 큰 크기에서 가장 작은 크기로 역순으로 검정해야 합니다.네, 코드를 작성해 드릴 수도 있었지만, 위의 내용을 실제 스크립트로 만들 수 있을 정도로 충분히 알고 계실 거라고 생각합니다.그것은 단지 당신을 당황하게 했던 접근법입니다.

스튜어트 "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
    }
  }

여러 if/switch 대신 값이 올바른 크기가 될 때까지 잠시 루프를 사용하는 것이 좋습니다.그것은 확장됩니다!

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

WSL이 있는 경우 PWSH에서 직접 호출할 수 있습니다.

wsls-sls-message

exa를 사용하면 더욱 좋습니다.

wslexa -l /mnt/c

한 가지 단점은 탭 완성이 당신에게 줄 것이라는 것입니다..\folder1\folder2에서 작동하지 않는exa슬래시를 대체하는 사용자 정의 함수를 작성합니다.

Function ll { 
  $target = ''
  if($args[0]){
    $target = $args[0] -replace "`\\","`/"
  }
  wsl exa -l --group --icons --sort=modified $target 
}

위에 올려놓으세요.$PROFILE로 철하다.notepad.exe $PROFILE그리고 pwsh를 다시 로드합니다.. $PROFILE.

지금이다ll정보가 잘 표시되고 탭 완료는 다음과 같은 하위 디렉토리에서 작동합니다.

ll .\subDir\subSubDir.

언급URL : https://stackoverflow.com/questions/24616806/powershell-display-files-size-as-kb-mb-or-gb

반응형