Wednesday, November 21, 2012

Powershell Format String with -F

Using String.Format in Powershell is very easy. Simply do as follows:

" My Name is {0} and I am {1} years old" -f  "Reuben", "27"

This will output

My Name is Reuben and I am 27 years old.

We can also add operators to transform the string. Below is a table.

OperatorExampleResultsDescription

{0}Display a particular element"{0} {1}" -f "a", "b"a b
{0:x}Display a number in Hexadecimal"0x{0:x}" -f 1813420x2c45e
{0:X}Display a number in Hexadecimal uppercase"0x{0:X}" -f 1813420x2C45E
{0:dn}Display a decimal number left justified, padded with zeros"{0:d8}" -f 300000003
{0:p}Display a number as a percentage"{0:p}" -f .12312.30 %
{0:c}Display a number as currency"{0:c}" -f  12.34$12.34
{0,n}Display with field width n, left aligned"|{0,5}|" -f "hi"|   hi|
{0,-n}Display with field width n, right aligned"|{0,-5}| -f "hi"|hi   |
{0:hh}
{0:mm}
Display the hours and minutes from a date time value"{0:hh}:{0:mm}" -f (Get-Date)01:34
{0:C}Display using the currency symbol for the current culture"|{0,10:C}|" -f 12.3|    $12.40|



Reference:
http://msdn.microsoft.com/en-us/library/26etazsy(VS.71).aspx

No comments: