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?
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.
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.
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.
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.
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)} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With