Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Formatting With PowerShell

1,756 views

Published on

This is a slide deck from a web cast I gave 2012. It looks at how you can do cool formatting things in PowerShell. Aimed at PowerShell v2, but everything there works in V3.

  • Be the first to comment

Formatting With PowerShell

  1. 1. MONTHLY WEBCAST Formatting with PowerShell Thomas Lee PowerShell MVP doctordns@gmail.com
  2. 2. MONTHLY WEBCASTAgenda Formatting by default Formatting using Format-table, Format-List Using .NET format Strings Formatting using.ToString() Formatting with Hash Tables Formatting XML Other output mechanisms
  3. 3. MONTHLY WEBCASTFormatting by Default PowerShell formats output by default  Useful for simple queries  Used by application cmdlet sets Formatting is controlled by Format.PS1XML files  Seven are installed by default You can  Edit built in files – but don’t…  Add new ones in your profile
  4. 4. MONTHLY WEBCASTThe Formatting Process The default formatting process Cmdlet or Format-Table or Out-Default Pipeline Format-List Formatted Output On Console
  5. 5. MONTHLY WEBCASTThe Formatting Process User Defined Formatting Cmdlet or Format-Table or Out-Default Pipeline Format-List Formatted Output On Console
  6. 6. MONTHLY WEBCASTThe Formatting Process Other Options Out-Gridview Cmdlet or Pipeline Out-* Cmdlets Text, CSV, XML
  7. 7. MONTHLY WEBCASTFormat-Table and Format-List Cmdlets take objects from pipeline – create table/list Default contents and ‘shape’ determined by .ps1xml You can override default properties  GWMI win32_ComputerSystem | fl name,model Can also take a hash table for precise format control
  8. 8. MONTHLY WEBCASTFormat-Wide Used to print a single property as a table
  9. 9. MONTHLY WEBCASTFormat-* vs Out-* The Format-* cmdlets format objects in the pipeline  You can adjust the details of how you want your data to appear using the cmdlets, hash tables, format strings, etc  They produce format objects The Out-* cmdlets take format objects and output it to the console (and elsewhere) Both are composed at the end of a pipeline
  10. 10. MONTHLY WEBCASTFormat-* Useful Parameters Format-Table  -Autosize  Creates columns of just required width for easier reading  Waits till ALL objects are ready before formatting  -HidetableHeaders  Hides table headers  -Wrap  Wraps long text into single column Format-List and Format-Table  -GroupBy  But you need to sort first
  11. 11. MONTHLY WEBCASTHow Default Formatting Works Objects in the pipeline - send to Out- Default Out-Default looks at the objects in the pipeline If formatting instructions – send to Out- Host If objects - send to Format-List or Format- Table
  12. 12. MONTHLY WEBCASTFormat.PS1XML Format.PS1XML sets default output  1st view is used if defined – if not format all properties  Four or less properties – call Format-Table  Otherwise call Format-List This creates format objects  Sent to Out-Default and then to the console
  13. 13. MONTHLY WEBCASTDefault Formatting in Use At the command line, you  Use the default  Pipe to FT/FL Or you pipe to FT/FL but adjust properties In scripts default formatting replaces specific output statements
  14. 14. MONTHLY WEBCAST.NET Composite Format Strings Composite String – string with placeholders  "I count {0} ps1 files there" –f (ls C:foo*.ps1).count Placeholder Syntax  {index[,alignment]{:formatstring}] Simple placeholder examples  {0}  {0,20}  {0,-20:n} Use these along with the –f operator and .NET formats values into the composite string
  15. 15. MONTHLY WEBCASTComposite Formatting Examples Fixed decimal point  $a=123.4567898  "{0:#.000}"  123.456 # culture sensitive Currency  $a=123456.789123  "{0:c2)"  £123,456.79 # culture sensitive Phone Number  $a=4255551212  "{0:(###) ###-####}" -f $a  (425) 555-1212
  16. 16. MONTHLY WEBCAST.ToString() All base types have a .ToString() method  Inherited from [Object]  Relied on to convert the object to a printable form  Can take parameters! Base types have power over how to format Pass a format string to .ToString() to control formatting Example  $i = 23.123456  $i.tostring("N2")  23.12
  17. 17. MONTHLY WEBCAST.NET Format Strings Numeric format strings  http://msdn.microsoft.com/en- us/library/427bttx3(VS.71).aspx Date and time format strings  http://msdn.microsoft.com/en- us/library/97x6twsz(VS.71).aspx Enumeration format strings  http://msdn.microsoft.com/en- us/library/c3s1ez6e(VS.71).aspx
  18. 18. MONTHLY WEBCASTFormatting with Hash Tables Uses a Hash Table with pre-defined key names:  Name (or Label) - <string>  Expression - <string> or <script block>  FormatString - <string>  Width - <int32>  Alignment (value can be "Left", "Center", or "Right") Send FT/FL hash table vs a property name
  19. 19. MONTHLY WEBCASTHash Table Example$Pn=@{label="Process Name"; Expression={$_.name}; alignment="right"}$Cpu=@{label="CPU Used"; Expression={$_.CPU}; FormatString="N3"}Get-Process notepad| Format-Table $Pn,$Cpu -auto
  20. 20. MONTHLY WEBCASTMore Hash Table Examples $Pn= @{ label = "Process Name"; Expression = {$_.name}; alignment = "right"} $Cpu=@{ label = "CPU Used"; Expression = {$_.CPU}; FormatString = "N1"} Get-Process | Format-Table $Pn,$Cpu –autosize $Pn2 = @{label ="Process Name"} $Pn2 += @{Expression={$_.name}} Get-Process | Format-List $Pn2,$Cpu
  21. 21. MONTHLY WEBCASTOther Output Mechanisms XML  Import-CliXML  Export-CliXML  ConvertTo-XML To a grid  Out-Gridview CSV  Export-CSV (and Import-CSV)
  22. 22. MONTHLY WEBCASTOut-GridView Uses WPF  You need latest .NET Framework Creates sortable list in a separate window with criteria to help limit output
  23. 23. MONTHLY WEBCASTOut-GridView Gotchas Out-GridView(and PowerShell ISE) need .NET 3.5 SP1  The rest of PowerShell requires .NET 2.0  Out-Gridview and ISE use WPF Out-Gridview displays the same columns as FT  Clone the object first to see all object properties Get-Process | Select-Object * | Out-Gridview
  24. 24. MONTHLY WEBCASTFormatting and .PS1XML Two types of ps1xml  Define/update types - *.types.ps1xml  Define/update formatting - *.format.ps1xml Default Format XML shipped with PowerShell  Apps or OS additions add to this default set  Stored in $Pshome DO NOT EDIT THESE FILES!  They are signed – editing breaks that!  Copy and create your own
  25. 25. MONTHLY WEBCASTFormatting XML Don’t like the way PowerShell formats a type?  Develop your own display XML PowerShell ships with 7 format.ps1xml files You can write your own  Define four views: table, list, wide, and complex  Do NOT edit existing files – make a copy and edit it Run Update-FormatData to add new view  Add this to $profile to persist the changea
  26. 26. MONTHLY WEBCASTFormatting XML Don’t like the way PowerShell formats a type?  Develop your own display XML PowerShell ships with 7 format.ps1xml files You can write your own  Define four views: table, list, wide, and complex  Do NOT edit existing files – make a copy and edit it Run Update-FormatData to add new view  Add this to $profile to persist the change
  27. 27. MONTHLY WEBCASTCreate a Class Using Add-Type Add-Type @ public class aeroplane { public string Model = "Boeing 737"; public int InFleet = 12; public int Range = 2400; public int Pax = 135; } @  But what about the display?
  28. 28. MONTHLY WEBCASTCreate XML – Step 1 <Name>  Identifies the name of the view. <ViewSelectedBy>  Specifies the object type or types to which the view applies. <GroupBy>  Specifies how items in the view should be combined in groups. <TableControl> <ListControl> <WideControl> <ComplexControl>  Contain the tags that specify how each item is displayed.
  29. 29. MONTHLY WEBCAST TableControl<TableControl> <TableHeaders> <TableColumnHeader> <label>Passengers</label><width>12</width> </TableColumnHeader> … </TableHeaders> <TableRowEntries> <TableRowEntry> <tableColumnItem><PropertyName>Pax</PropertyName></tablecolumnitem> </TableRowEntry> … </TableRowEntries></TableControl>
  30. 30. MONTHLY WEBCASTList Control<ListControl> <ListEntries> <ListEntry> <ListItems> <ListItem> <PropertyName>Model</PropertyName> </ListItem> … <ListItems> <ListEntry> </ListEntries></Listcontrol>
  31. 31. MONTHLY WEBCASTCombine It Together Save XML to c:fooaeroplane.format.ps1xml Update-FormatData –Prepend c:fooaeroplane.format.ps1xml Then:  $AP = new-object aeroplane  $AP  $AP | fl
  32. 32. MONTHLY WEBCASTUsing Type/Format Updates Create the XML  On your workstation  XCOPY during logon script? Store it somewhere useful  C:foo  Somewhere else?? Add the type/format information to $Profile  Update-FormatData –prepend –Path <path>
  33. 33. MONTHLY WEBCASTSummary Formatting can be simple or complex Lots of alternatives – have it your way Keep it simple and extend to meet your needs
  34. 34. MONTHLY WEBCASTAdding To Your Profile Possibly add some default format hash tables for commonly used outputs
  35. 35. MONTHLY WEBCASTResources Formatting - see my articles on formatting  http://tfl09.blogspot.com/2010/02/formatting- with-powershell.html .NET Formatting  http://msdn.microsoft.com/en- us/library/txafckwd(VS.71).aspx
  36. 36. MONTHLY WEBCASTQuestions ?? ?? ??

×