Wednesday, January 18, 2012

Training Questions: Date and Numeric Formatting with PowerShell

At a recent internal training session, I was asked how to format dates in PowerShell. A little later I was asked how to format numbers, and later still I was asked if it was possible to right justify strings. Following is the example I used to demonstrate the formating capabilities:

Get-ADUser SamAccountName -Properties WhenCreated | 
Select SamAccountName,WhenCreated,
@{Name="ShortDate"; Expression={ "{0:d}" -f $_.WhenCreated} },
@{N="LongDate";E={ "{0:D}" -f $_.WhenCreated} },
@{L="FullDateShortTime";E={ "{0:f}" -f $_.WhenCreated} },
@{N="FullDateLongTime"; E={ "{0:F}" -f $_.WhenCreated} },
@{N="GeneralDateShortTime";E={ "{0:g}" -f $_.WhenCreated} },
@{N="GeneralDateLongTime"; E={ "{0:G}" -f $_.WhenCreated} },
@{N="Month";E={ "{0:M MM MMM MMMM}" -f $_.WhenCreated} },
@{N="Day"; E={ "{0:d dd ddd dddd}" -f $_.WhenCreated} },
@{N="Year"; E={ "{0:y yy yyy yyyy}" -f $_.WhenCreated} },
@{N="Hour"; E={ "{0:h hh H HH}" -f $_.WhenCreated} },
@{N="Minute"; E={ "{0:m mm}" -f $_.WhenCreated} },
@{N="Second"; E={ "{0:s ss}" -f $_.WhenCreated} },
@{N="AM/PM"; E={ "{0:t tt}" -f $_.WhenCreated} },
@{N="CustomDateTime1"; E={ "{0:M/d/yy h:m:s tt}" -f $_.WhenCreated} },
@{N="CustomDateTime2"; E={ "{0:dddd, MMMM yyyy - HH:mm:ss}" -f $_.WhenCreated} }

Get-WmiObject -Class win32_logicalDisk -Filter "DeviceID='C:'" |
Select DeviceID, FreeSpace,
@{N="FreeSpaceDecimal"; E={ "{0:d}" -f $_.FreeSpace} },
@{N="FreeSpaceScientific1"; E={ "{0:E}" -f $_.FreeSpace} },
@{N="FreeSpaceScientific2"; E={ "{0:E1}" -f $_.FreeSpace} },
@{N="FreeSpaceFixed1"; E={ "{0:F1}" -f $_.FreeSpace} },
@{N="FreeSpaceFixed2"; E={ "{0:F5}" -f $_.FreeSpace} },
@{N="FreeSpaceGeneral"; E={ "{0:G3}" -f $_.FreeSpace} },
@{N="FreeSpaceNumber"; E={ "{0:N3}" -f $_.FreeSpace} },
@{N="FreeSpacePercent"; E={ "{0:P}" -f ($_.FreeSpace/$_.Size)} },
@{N="FreeSpaceGB"; E={ "{0:N0} GB" -f ($_.FreeSpace/1GB)} }

$myString = "Yuengling"
"{0,10}" -f $myString
"{0,15}" -f $myString
"{0,20}" -f $myString

Results:


Enjoy!

1 comment:

MLO said...

Here's a challenge for you. Try displaying the whenCreated value in table format.