ConvertTo-LargestByteSize

Topics: Archive - Toolkit Extensions
Developer
Sep 28, 2014 at 6:56 AM
Function ConvertTo-LargestByteSize
{
<#
.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
    
.EXAMPLE
    ConvertTo-LargestByteSize -Size 568956
    555 KB
    
    Description
    -----------
    Converts the byte value 568956 to upper most value of 555 KB
    
.EXAMPLE
    Get-ChildItem  |
    Where-Object {-not ($_.PSIsContainer)} |
    Select-Object -First 5 |
    Select-Object -Property Name, @{L='Size';E={$_ | ConvertTo-LargestByteSize}}
    
    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.
    
.NOTES
.LINK
#>
    [CmdletBinding()]
    Param
    (
        [Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [long]$Size
    )
    Begin
    {
        $ConvertToLargestByteSizeSource =  @'
        using System;
        using System.Text;
        using System.Runtime.InteropServices;
        
        namespace Convert
        {
            public class Byte
            {
                [DllImport("shlwapi.dll", CharSet = CharSet.Auto)]
                public static extern long StrFormatByteSize(long fileSize, StringBuilder buffer, int bufferSize);
                
                public static string ConvertToLargestByteSize(long size)
                {
                    const int nChars = 256;
                    StringBuilder Buff = new StringBuilder(nChars);
                    
                    StrFormatByteSize(size, Buff, Buff.Capacity);
                    return Buff.ToString();
                }
            }
        }
'@
        If (-not ([System.Management.Automation.PSTypeName]'Convert.Byte').Type)
        {
            Add-Type -TypeDefinition $ConvertToLargestByteSizeSource -Language CSharp
        }
    }
    Process
    {
        Write-Log "Converting [$Size bytes] to upper most size"
        [string]$LargestByteSize = [Convert.Byte]::ConvertToLargestByteSize($Size)
        Write-Output $LargestByteSize
    }
}