PowerTip: Formatting Numeric Output Using PowerShell

PowerTip: Formatting Numeric Output Using PowerShell

  • Comments 6
  • Likes

Summary: Learn how to format numeric output in Windows PowerShell by using format specifiers and numeric constants.

Hey, Scripting Guy! Question How can I print the amount of free space on a fixed disk in MB with two decimal places?

Hey, Scripting Guy! Answer Use a format specifier as shown here:

"{0:n2}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1MB)

Hey, Scripting Guy! Question What if I want to display the output in GB with three decimal places?

Hey, Scripting Guy! Answer Use a format specifier as shown here:

"{0:n3}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1GB)

Hey, Scripting Guy! Question I like big numbers. Can I display it in KB and have five decimal places?

Hey, Scripting Guy! Answer Use a format specifier as shown here:

"{0:n5}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1KB)

Hey, Scripting Guy! Question I want something simple. Can I print the amount of free space on a fixed disk in MB in whole numbers?

Hey, Scripting Guy! Answer No need for a format specifier, as shown here:

[int] ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1MB)


Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • This is my favorite:

    0x{0:x}' -f -2147467259

  • Second favorite:

    [System.Convert]::ToString(0x80004005,2)

  • @JRV that is cool. I do like it as well -- it is also one of my favorites.

  • I always seem ot get stuck "bit twiddling".  PowerShell makes this a cinch.  No more scientific calculator as PowerShell is my new scientific and programmable calculator.

    Now maybe Mathametica will be ported to PowerShell making PowerShell a super scientific calculator.

  • If there is only a single value to format using ToString(format) is probably clearer than -f (or, its underlying, String.Format):

    So

    "{0:n5}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1KB)

    becomes

    ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1KB).ToString("n5")

  • @rjcox - I like that.  It is a very convenient way to grab a reformatted single value.