PowerTip: Formatting Numeric Output Using PowerShell

Doctor Scripto

Dr Scripto

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)


0 comments

Comments are closed.