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

In Powershell, I would like to convert the $ size variable from bytes to gigabytes GB. What is the best way to do this? So far I have the following script:

$dir = "C:\Users\student" $count = @{} $size = @{} $hostname = @{} gci $dir -recurse |%{ [int]$count[$_.extension] += 1 [int64]$size[$_.extension] += $_.length } $results = @() $count.keys | sort |% { $result = ""|select extension,count,size,hostname $result.extension = $_ $result.count = $count[$_] $result.size = $size[$_] $result.hostname = $(get-content env:computername) $results += $result } $results | ft -auto $results | sort-object -property size -Descending | select-object -first 30| export-csv c:\"$env:computername-$(get-date -f dd-MM-yyyy-HH-mm)".csv 
+4
source share
3 answers

there is a trick for him

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

and if you need a better view of the results, you can crop it

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

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

+10
source

I will add one more tip in response from sqladmin.

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

Hope it helps.

0
source

as long as you have the main answer [smirk], this is a variant of the method of collecting / processing / collecting / displaying information.

it uses the -AsHashTable Group-Object parameter to build an extension lookup table. then iterates over the keys, replaces the empty extension key with the placeholder name, calculates the file size, creates [PSCustomObject] and finally sends it 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 
0
source

Source: https://habr.com/ru/post/1489662/


All Articles