Hi,
Yesterday I was using –F format Operator in PowerShell. In the first view it seems like puzzle me to but after spending few hours working on it start seems simple.
-F format operator is basically a .NET based.
Why we need to use the –F format operator?
Yes we have few cmdlets by using them we can format the output, but by using –F format operator we can do more than that.
SYNTAX
The syntax for –F format operator is
{<index>[,<alignment>][:<formatString>]}
| |
Format Strings | Description |
C | Currency |
X | Display Number in Hexa Decimal |
p | Display Number as Percentage |
n | Display with width n to left side |
-n | Display with width –n to right side |
dn | Display Numbers Padded by 0 by n times |
# | Digit placeholder, |
, | Thousand separator |
\ | Escape Character |
:ddd | Day of Week |
:dd | Day of Month |
:dddd | Full name of Day of Week |
:hh | Hour |
:HH | Hour in 24 Hour format |
:mm | Minutes |
:SS | Seconds |
:MM | Month in Number |
:MMMM | Name of the Month |
:yy | Year in short |
:yyyy | Full year |
In –F format operator we provide the strings and numbers in the right hand side and stantax for –F in left hand side.
Position
In below example we are just querying the first number in our right hand side. The first number is 1,
"{0}" -f 1,2,3,4,5
Ok now let’s add some space in our first number.
"{0,10}" -f 1,2,3,4,5
You can see that the Position of “1” is moved to little bit on right hand side.
· :c or :C | Currency
"{0:C}" -f 200,99,765
You can see that now the output is in currency.
Let’s choose the second number
"{1:C}" -f 200,99,765
· :x or :X | Hexa Decimal
"{0:x}" -f 909887
It Converted the Number 909887 to hexadecimal value.
· :p | Percentage
"{0:p}" -f .703
Output is in Percentage.
· :dn | Padded 0
"{0:d7}" -f 9
We specified to add 7 zeros but it added 6 , actually it added 7 and the last 0 replaced by the decimal number.
· # | Digit Place Holder
"{0:###-##-##}" -f 8976203
When we use # in format operator the # are replaced by the digits.
· Date and Time Formater
"{0:ddd}" -f (get-date)
"{0:dd}" -f (get-date)
"{0:dddd}" -f (get-date)
"{0:hh}" -f (get-date)
"{0:mm}" -f (get-date)
"{0:MM}" -f (get-date)
"{0:MMMM}" -f (get-date)
"{0:yy}" -f (get-date)
"{0:yyyy}" -f (get-date)
· ,| Thousand separator
"{0:#,#}" -f 100980243
· Practice Example
$pro = Get-Process
foreach ($a in $pro) {
"{0,20} {1,40}" -f $a.ProcessName , $a.vm
}
Try the above script and the output should be like this .
USEFUL Links :
http://msdn.microsoft.com/en-us/library/26etazsy.aspx
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.