Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1238
  • Last Modified:

Converting data to KB, MB, GB

I have been trying to convert raw numbers in a file to KB, GB or MB. For ex


get-content c:\temp\numbers.txt | select -object Name, {$_.Somename.value.ToMB()}

the text file contain numbers of different sizes that were recorded from another sheet.

or I would really like to pipe it into something like this


  $_ | Select-Object Name, @{n='Count';e={ $Count }}, @{n='Size';e={
    If     ($Size -gt 1GB) { "$('{0:N2}' -f ($Size / 1Gb)) GB" }
    ElseIf ($Size -gt 1MB) { "$('{0:N2}' -f ($Size / 1Mb)) MB" }
    ElseIf ($Size -gt 1KB) { "$('{0:N2}' -f ($Size / 1Kb)) KB" }
    Else                   { "$Size b" } }}
0
techdrive
Asked:
techdrive
  • 2
  • 2
1 Solution
 
Chris DentPowerShell DeveloperCommented:
It's not quite as complex as the two snippets you have.
Get-Content c:\temp\numbers.txt | ForEach-Object {
  If ($_ -gt 1GB) { 
    "$('{0:N2}' -f ($_ / 1Gb)) GB" 
  } ElseIf ($_ -gt 1Mb) {
    "$('{0:N2}' -f ($_ / 1Mb)) MB"
  } ElseIf ($_ -gt 1Kb) {
    "$('{0:N2}' -f ($_ / 1Kb)) KB"
  } Else {
    "$_ b"
  }
}

Open in new window

Is that what you had in mind?

Chris
0
 
techdriveAuthor Commented:
The logic is nice however I am getting the following below when I run this

Cannot compare "@{Name=439150512}" to "1073741824" because the objects are not the same type or the object "@{Name=439150512}" does not implement "IComparable".
At C:\temp\convert.ps1:2 char:13
+   If ($_ -gt <<<<  1GB) {
    + CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
    + FullyQualifiedErrorId : PSObjectCompareTo
0
 
Chris DentPowerShell DeveloperCommented:
What exactly do you have in that text file of yours?

Chris
0
 
techdriveAuthor Commented:
Chris sorry the machine I was using is locked down. This worked perfectly thanks again.
0

Featured Post

Evaluating UTMs? Here's what you need to know!

Evaluating a UTM appliance and vendor can prove to be an overwhelming exercise.  How can you make sure that you're getting the security that your organization needs without breaking the bank? Check out our UTM Buyer's Guide for more information on what you should be looking for!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now