Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell display files size as KB, MB, or GB

Tags:

I have a section of a PowerShell script that gets the file size of a specified directory.

I am able to get the values for different units of measurement into variables, but I don't know a good way to display the appropriate one.

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

If the number of bytes is at least 1 KB I want the KB value displayed. If the number of KBs is at least 1 MB I want MBs displayed and so on.

Is there a good way to accomplish this?

like image 800
NebDaMin Avatar asked Jul 07 '14 17:07

NebDaMin


People also ask

How do I check the size of a file in PowerShell?

Use the Length Property to Get File Size in KB Using PowerShell. The file objects have the Length property in PowerShell. It represents the size of the file in bytes.

How do I find the file size in kb?

Step 2: Multiply total number of pixels by the bit depth of the detector (16 bit, 14 bit etc.) to get the total number of bits of data. Step 3: Dividing the total number of bits by 8 equals the file size in bytes. Step 4: Divide the number of bytes by 1024 to get the file size in kilobytes.

How do I see the size of a folder in PowerShell?

You can use the Get-ChildItem ( gci alias) and Measure-Object ( measure alias) cmdlets to get the sizes of files and folders (including subfolders) in PowerShell.

How do you convert MB to GB in PowerShell?

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.


1 Answers

There are lots of ways to do this. Here's one:

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)} } 
like image 161
mjolinor Avatar answered Sep 20 '22 14:09

mjolinor