August 14th, 2012

PowerTip: Formatting Numeric Output Using PowerShell

Doctor Scripto
Scripter

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)


Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.