Welcome Forums General PowerShell Q&A Simple Formatting of Output

Viewing 3 reply threads
  • Author
    Posts
    • #49784
      Participant
      Topics: 18
      Replies: 28
      Points: 38
      Rank: Member

      I am trying to get the @{n=’length (MB)’;e= {$_.length/1MB}} to display in say 15.47 and not 15.477776998, is there an easy way to get this formatting in the below powershell?

      $filepath = “C:\temp”

      $Items = Get-ChildItem -Path $filepath -Recurse -Force

      $files = $items | ? {!$_.PsIsContainer }

      $files | Select-Object -Property @{n=’FileName’;e={$_.name.ToUpper()}}, @{n=’length (MB)’;e= {$_.length/1MB}} | Sort-Object -Property ‘length (MB)’ -Descending | Out-GridView

    • #49793
      Moderator
      Topics: 2
      Replies: 525
      Points: 24
      Team Member
      Rank: Member

      Hi Andrew,

      You’ve got two options:

      1. Round the numbers to the specified number of decimal places:

      [System.Decimal]::Round($_.Length/1MB, 2)

      https://gist.github.com/Dan1el42/39766db12a3df808eabe0aff44039676

      2. Convert it to a string and format it using the .NET formatting feature:

      ($_.Length/1MB).ToString(‘N2’)

      https://gist.github.com/Dan1el42/5a809c0157202709769a5f8503357e97

      I hope that helps.

      Cheers
      Daniel

    • #49797
      Participant
      Topics: 18
      Replies: 28
      Points: 38
      Rank: Member

      Thanks Daniel – been banging my head on the wall for a while – cheers

    • #49850
      Keymaster
      Topics: 13
      Replies: 4872
      Points: 1,896
      Helping HandTeam Member
      Rank: Community Hero

      I’d have….

      $files | Select-Object -Property @{n='FileName';e={$_.name.ToUpper()}}, @{n='length (MB)';e={ '{0:N2}' -f ($_.length/1MB) } | Sort-Object -Property 'length (MB)' -Descending | Out-GridView
      

      Formatting (-f) operator. Uses the same notation as the ToString() trick above.

Viewing 3 reply threads
  • The topic ‘Simple Formatting of Output’ is closed to new replies.