How to convert a $size variable from bytes into GB in Powershell? How to convert a $size variable from bytes into GB in Powershell? powershell powershell

How to convert a $size variable from bytes into GB in Powershell?


there is a trick for it

$result.size = $size[$_] /1Gb

and if you want better view for results you can truncate it

$result.size = [math]::round($size[$_] /1Gb, 3)

http://technet.microsoft.com/en-us/library/ee692684.aspx


I'll add another tip to the Answer from sqladmin.

If the object is stored in byes then [math]::round($size[$_] /1Gb, 3) will work. If it is stored in another unit (for example, Database.Size Property is in MB) then you can multiply it by the unit of measure and divide by GB. So for MB unit: @{Name="Size(GB)";Expression={[math]::round($_.size*1MB/1GB,4)}}.

Hope it helps.


while you have your basic answer [grin], this is a variant way to gather/process/collect/output the info.

it uses the -AsHashTable parameter of Group-Object to build the extension lookup table. then iterates thru the keys, replaces the blank extension key with a filler name, calcs the file size, builds a [PSCustomObject], and finally sends it out to the collection.

$SourceDir = $env:TEMP# the "-Force" parameter includes the hidden & system files#    without = 503 files#    with    = 535 files$FileList = Get-ChildItem -LiteralPath $SourceDir -File -Recurse -Force$FileTypesTable = $FileList |    Group-Object -AsHashTable -Property Extension$TypeInfo = foreach ($FTT_Item in $FileTypesTable.Keys)    {    $Extension = @('_No_Ext_', $FTT_Item)[[bool]$FTT_Item]    $Size_Bytes = ($FileTypesTable[$FTT_Item].Length |            Measure-Object -Sum).Sum    [PSCustomObject]@{        Extension = $Extension        Count = $FileTypesTable[$FTT_Item].Count        Size_GB = [math]::Round($Size_Bytes / 1GB, 4)        #Size_Bytes = $Size_Bytes        }    }$TypeInfo |    Sort-Object -Property Size_GB -Descending

output ...

Extension Count Size_GB--------- ----- -------.msi          1  0.2637.exe         35  0.1568.wmv          4  0.0978.mp3         12  0.0647.log        142  0.0579.zip          3  0.0454.jpg         32  0.0217.csv         67  0.0044.xpi          1  0.0031.txt        116  0.0026_No_Ext_      7  0.0023.part         1  0.0023.ico         24  0.0001.bat         18       0.m3u8         1       0.json         1       0.xls          8       0.ps1          1       0.js           1       0.xml          4       0.mp4          8       0.ani          1       0.ini         25       0.tmp         21       0.bmp          1       0