1 / 45

Formatting with PowerShell

Thomas Lee ( tfl@psp.co.uk ) MCT PowerShell MVP. Formatting with PowerShell. Who am I?. MCT PowerShell MVP Worked with, trained and written about PowerShell for years! SME on 6434 and TR on 10325 official MOC classes. Giveaway. I have 25 copies of PowerShell Plus

jethro
Download Presentation

Formatting with PowerShell

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Thomas Lee (tfl@psp.co.uk) MCT PowerShell MVP Formatting with PowerShell

  2. Who am I? • MCT • PowerShell MVP • Worked with, trained and written about PowerShell for years! • SME on 6434 and TR on 10325 official MOC classes

  3. Giveaway • I have 25 copies of PowerShell Plus • http://www.idera.com/Products/PowerShell/PowerShell-Plus/ or • http://tinyurl.com/psplus • To win: • You need to email me with a code word. • Email me at tfl@psp.co.uk • The code word will be at the end of the presentation

  4. What I assume about you • Know a bit (or more) about PowerShell • At least to the level of the earlier Summit session! • You know what a cmdlet is, what the pipeline does and what objects are • And you want to do more with formatting • If you want to type-along with me, feel free!

  5. Agenda • Formatting by default • Formatting using Format-table, Format-List • Using .NET format Strings • .ToString() • Formatting using Hash Tables • Formatting XML • Other output mechanisms • Some thoughts on style etc

  6. Formatting by Default • PowerShell formats output by default • Useful for simple queries • Formatting is controlled by Format.PS1XML files • Seven are installed by default • LS $PSHOME\*.Format.PS1.XML • You can • You can edit built in Format.PS1XML files - but don’t… • Instead, add new ones and ‘install’ in Profile

  7. The Formatting Process • The default formatting process Cmdlet orPipeline Out-Default Format-Table or Format-List Formatted Output On Console

  8. The Formatting Process • User Defined Formatting Cmdlet orPipeline Format-Table or Format-List Out-Default Formatted Output On Console

  9. The Formatting Process • Other Options Out-Gridview Cmdlet orPipeline Cmdlets Text, CSV, XML

  10. Format-Table and Format-List • Cmdlets take objects from pipeline – create table/list • Default contents and ‘shape’ determined by .ps1xml • You can override defaults, for example: • GWMI win32_ComputerSystem | fl name,model • Can also take a hash table for precise format control

  11. Format-Wide • Used to print a single property as a table

  12. Format-* vs Out-* • The Format-* cmdlets format objects • Om the pipeline or via –Inputobject parameter • 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)

  13. Format-* Useful Parameters • Format-Table • -Autosize • Waits till ALL objects are ready before formatting and auto-sizes the width of each column • -HidetableHeaders • Hides table headers • Format-List and Format-Table • -GroupBy • But you need to sort first

  14. How Default Formatting Works • Objects in the pipeline are sent to Out-Default • Out-Default looks at the objects in the pipeline • If formatting instructions – send it to Out-Host • If objects - send to Format-List or Format-Table • Out-Default looks in .PS1XML for guidance • Select 1st view for guidance • Five or less properties – call Format-Table • Otherwise call Format-List • This creates format objects • Sent to Out-Default and then to the console

  15. Basic Formatting, and more • You can get basic output from PoweShell using default formatting • You can see more/different using Format-table/list directly • FL/FT typically used at the end of a pipeline • But PowerShell is built on .NET • Lets leverage .NET formatting

  16. .NET Composite Format Strings • Composite String – with placeholders • "There are{0} ps1 files" –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 • .NET formats values into the composite string!

  17. Composite Formatting Examples • Fixed decimal point • $a=123.4567898 • "The Number is: {0:#.000}" –f $a • The Number is: 123.456 • Currency • $a=123456.789123 • "{0:c2}" –f $a • £123,456.79 • Phone Number • $a=4255551212 • "{0:(###) ###-####}" -f $a • (425) 555-1212

  18. .ToString() • All types have a .ToString()method • Inherited from [Object] • 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

  19. Using .NET Formatting • Format output for a single related set of values • Number of files • Number of files and their total size • Also use it to format one line in a table • Foreach ($file in $files) {display some aspect(s) of each file} • .NET Formatting string used in • Composite format string • ToString() • Hash Tables (later in this talk)

  20. .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

  21. Simple Formatting Demo 1

  22. Formatting with Hash Tables • Using FT/FL, you can create a ‘calculated field’ • Field defined by 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

  23. Hash Table Example $x1=@{label="Process Name"; Expression={$_.name}; alignment="right"} $x2=@{label="CPU Used"; Expression={$_.CPU};FormatString="N3"} Get-Process notepad | Format-Table $x1,$x2 -auto

  24. Another Hash Table Example $x1=@{label="Process Name";Expression={$_.name}; alignment="right"} $x2=@{label="CPU Used"; Expression={$_.CPU};FormatString="N3"} Get-Process | Format-Table $x1,$x2 –autosize $x3=@{label="Process Name"; Expression={$_.name}} Get-Process | Format-List $x3,$x2

  25. When To Use Hash tables • Give FT/FL better column/table headers • Sometimes property name is ugly/unhelpful • Display a calculated value • Covert a number into gb/mb etc • Expression = {$_.Length/1GB} • Coerce field into to nicer format easily

  26. Other Output Mechanisms • XML • Import-CliXML • Export-CliXML • ConvertTo-XML • CSV • Export-CSV (and Import-CSV) • Useful for interop with XML Applications

  27. Out-GridView • Uses WPF • You need latest .NET Framework • Creates sortable list in a separate window with criteria to help limit output

  28. Out-GridView Gotchas • Out-GridView (and PowerShell ISE) need .NET 3.51 • The rest of PowerShell requires .NET 2.0 • Out-Gridview and ISE use WPF • By default, Out-Gridview displays same columns as FT • Clone the object first to see all object properties • Get-Process | Select-Object * | Out-Gridview

  29. Hash tables and FT/FL Demo 2

  30. Where are we? • Seen default formatting • Used FT/FL and hash tables • Formatted using .NET • So let’s do create custom XML

  31. Formatting and .PS1XML • Two types of ps1xml • Define/update types - *.types.ps1xml • Define/update formatting - *.format.ps1xml • Default Format XML shipped with PowerShell • Apps , OS additions, modules add to this default set • Stored in $PSHOME • DO NOT EDIT THESE FILES! • They are signed – editing breaks that! • Copy and edit them instead

  32. Formatting 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-FormatDatato add new view • Add this to $profileto persist the change

  33. The XML • <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.

  34. Create 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? • Use FormatData.ps1xml

  35. Create a .FormatData.PS1XML <Configuration> <ViewDefinitions> <View> <name>Airplane</name> <TableControl>…</TableControl> </View> <View> <name>Airplane</name> <ListControl>…</ListControl> </View> </ViewDefinitions></Configuration> Saved as Aeroplane.formatdata.ps1xml Imported as needed/when needed

  36. TableControl <TableControl> <TableHeaders> <TableColumnHeader> <label>Passengers</label><width>12</width> </TableColumnHeader> … </TableHeaders> <TableRowEntries> <TableRowEntry> <tableColumnItem><PropertyName>Pax</PropertyName</tablecolumnitem> </TableRowEntry> … </TableRowEntries> </TableControl>

  37. List Control <ListControl> <ListEntries> <ListEntry> <ListItems> <ListItem> <PropertyName>Model</PropertyName> </ListItem> … <ListItems> <ListEntry> </ListEntries> </Listcontrol>

  38. Combine It Together • Save XML to C • Update-FormatData c:\foo\aeroplane.format.ps1xml • Then: $Object = new-object aeroplane $object $object | fl

  39. And while we’re talking XML • You can also extend existing types or add new ones • Create XML file describing your addition • Use Update-TypeData to incorporate it • Persist the change by updating $Profile

  40. Sample Type File <Types> <Type> <Name>System.Object</Name> <Members> <ScriptMethod> <Name>MSDN</Name> <Script> if (($global:MSDNViewer -eq $null) -or ($global:MSDNViewer.HWND -eq $null)) { $global:MSDNViewer = new-object -ComObject InterNetExplorer.Application} $Uri = "http://msdn2.microsoft.com/library/" + $this.GetType().FullName + ".ASPX" $global:MSDNViewer.Navigate2($Uri) $global:MSDNViewer.Visible = $TRUE </Script> </ScriptMethod> </Members> </Type> </Types>

  41. UsingType/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 your $Profile • Update-TypeData -Path <path> • Update-FormatData –Path <path>

  42. Summary • Formatting can be simple or complex • Lots of alternatives – have it your way • Keep it simple and extend to meet your needs

  43. Now For The FREE Stuff! • I have free copies of PowerShell Pro • Idera’s PowerShell Development Tool • The first 25 folks to email me will get a link to download the software (and a license). • I gave you the email address at the start of this presentation • The codeword is “POWERSHELLISAWESOME!” • The first 25 to mail that code word to the address I gave earlier will win their prize!

  44. Resources • Adding .MSDN() to types • http://blogs.msdn.com/powershell/archive/2006/06/24/644987 • Formatting - see TFL’s 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 • Thomas Lee’s Blogs/PowerShell site • http://tfl09.blogspot.com • http://pshscripts.blogspot.com • http://www.reskit.net/psmc

  45. The End

More Related