SlideShare une entreprise Scribd logo
1  sur  36
MONTHLY WEBCAST




       Formatting with PowerShell

                       Thomas Lee
                    PowerShell MVP
                  doctordns@gmail.com
MONTHLY WEBCAST




Agenda
   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
MONTHLY WEBCAST




Formatting 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
MONTHLY WEBCAST




The Formatting Process
 The default formatting process

     Cmdlet or                  Format-Table or
                  Out-Default
      Pipeline                    Format-List



                                Formatted Output
                                   On Console
MONTHLY WEBCAST




The Formatting Process
 User Defined Formatting

     Cmdlet or    Format-Table or
                                      Out-Default
      Pipeline      Format-List



                                    Formatted Output
                                       On Console
MONTHLY WEBCAST




The Formatting Process
 Other Options
                  Out-Gridview




     Cmdlet or
      Pipeline    Out-* Cmdlets




                  Text, CSV, XML
MONTHLY WEBCAST




Format-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
MONTHLY WEBCAST




Format-Wide
 Used to print a single property as a table
MONTHLY WEBCAST




Format-* 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
MONTHLY WEBCAST




Format-* 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
MONTHLY WEBCAST




How 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
MONTHLY WEBCAST




Format.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
MONTHLY WEBCAST




Default 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
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
MONTHLY WEBCAST




Composite 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
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
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
MONTHLY WEBCAST




Formatting 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
MONTHLY WEBCAST




Hash 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
MONTHLY WEBCAST




More 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
MONTHLY WEBCAST




Other Output Mechanisms
 XML
     Import-CliXML
     Export-CliXML
     ConvertTo-XML

 To a grid
     Out-Gridview

 CSV
     Export-CSV (and Import-CSV)
MONTHLY WEBCAST




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




Out-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
MONTHLY WEBCAST




Formatting 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
MONTHLY WEBCAST




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-FormatData to add new view
     Add this to $profile to persist the changea
MONTHLY WEBCAST




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-FormatData to add new view
     Add this to $profile to persist the change
MONTHLY WEBCAST




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?
MONTHLY WEBCAST




Create 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.
MONTHLY WEBCAST




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




List Control
<ListControl>
    <ListEntries>
        <ListEntry>
            <ListItems>
                <ListItem>
                    <PropertyName>Model</PropertyName>
                </ListItem>     …
            <ListItems>
        <ListEntry>
    </ListEntries>
</Listcontrol>
MONTHLY WEBCAST




Combine It Together
 Save XML to c:fooaeroplane.format.ps1xml
 Update-FormatData –Prepend
  c:fooaeroplane.format.ps1xml



 Then:
     $AP = new-object aeroplane
     $AP
     $AP | fl
MONTHLY WEBCAST




Using 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>
MONTHLY WEBCAST




Summary
 Formatting can be simple or complex
 Lots of alternatives – have it your way
 Keep it simple and extend to meet your
  needs
MONTHLY WEBCAST




Adding To Your Profile
 Possibly add some default format hash
  tables for commonly used outputs
MONTHLY WEBCAST




Resources
 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
MONTHLY WEBCAST




Questions
 ??
 ??
 ??

Contenu connexe

Tendances (19)

Sql server ___________session 3(sql 2008)
Sql server  ___________session 3(sql 2008)Sql server  ___________session 3(sql 2008)
Sql server ___________session 3(sql 2008)
 
Oracle SQL AND PL/SQL
Oracle SQL AND PL/SQLOracle SQL AND PL/SQL
Oracle SQL AND PL/SQL
 
e computer notes - Creating and managing tables
e computer notes -  Creating and managing tablese computer notes -  Creating and managing tables
e computer notes - Creating and managing tables
 
Les01
Les01Les01
Les01
 
MDI Training DB2 Course
MDI Training DB2 CourseMDI Training DB2 Course
MDI Training DB2 Course
 
Sas classes in mumbai
Sas classes in mumbaiSas classes in mumbai
Sas classes in mumbai
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql Syntax
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
SAS Access / SAS Connect
SAS Access / SAS ConnectSAS Access / SAS Connect
SAS Access / SAS Connect
 
Foxpro (1)
Foxpro (1)Foxpro (1)
Foxpro (1)
 
Commands of DML in SQL
Commands of DML in SQLCommands of DML in SQL
Commands of DML in SQL
 
SQL WORKSHOP::Lecture 1
SQL WORKSHOP::Lecture 1SQL WORKSHOP::Lecture 1
SQL WORKSHOP::Lecture 1
 
Les08-Oracle
Les08-OracleLes08-Oracle
Les08-Oracle
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Sap abap
Sap abapSap abap
Sap abap
 
Ddl &amp; dml commands
Ddl &amp; dml commandsDdl &amp; dml commands
Ddl &amp; dml commands
 
COIS 420 - Practice01
COIS 420 - Practice01COIS 420 - Practice01
COIS 420 - Practice01
 

En vedette

2014 SpiceWorld London Breakout
2014 SpiceWorld London Breakout2014 SpiceWorld London Breakout
2014 SpiceWorld London BreakoutThomas Lee
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101Thomas Lee
 
2015 spice world_london_breakout
2015 spice world_london_breakout2015 spice world_london_breakout
2015 spice world_london_breakoutThomas Lee
 
Three cool cmdlets I wish PowerShell Had!
Three cool cmdlets I wish PowerShell Had!Three cool cmdlets I wish PowerShell Had!
Three cool cmdlets I wish PowerShell Had!Thomas Lee
 
Coping with Murphy’s Law
Coping with Murphy’s LawCoping with Murphy’s Law
Coping with Murphy’s LawThomas Lee
 
2016 spice world_london_breakout
2016 spice world_london_breakout2016 spice world_london_breakout
2016 spice world_london_breakoutThomas Lee
 
Top 10 PowerShell Features in Server 2012
Top 10 PowerShell Features in Server 2012Top 10 PowerShell Features in Server 2012
Top 10 PowerShell Features in Server 2012Thomas Lee
 
NIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShellNIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShellPhan Hien
 

En vedette (8)

2014 SpiceWorld London Breakout
2014 SpiceWorld London Breakout2014 SpiceWorld London Breakout
2014 SpiceWorld London Breakout
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101
 
2015 spice world_london_breakout
2015 spice world_london_breakout2015 spice world_london_breakout
2015 spice world_london_breakout
 
Three cool cmdlets I wish PowerShell Had!
Three cool cmdlets I wish PowerShell Had!Three cool cmdlets I wish PowerShell Had!
Three cool cmdlets I wish PowerShell Had!
 
Coping with Murphy’s Law
Coping with Murphy’s LawCoping with Murphy’s Law
Coping with Murphy’s Law
 
2016 spice world_london_breakout
2016 spice world_london_breakout2016 spice world_london_breakout
2016 spice world_london_breakout
 
Top 10 PowerShell Features in Server 2012
Top 10 PowerShell Features in Server 2012Top 10 PowerShell Features in Server 2012
Top 10 PowerShell Features in Server 2012
 
NIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShellNIIT ISAS Q5 Report - Windows PowerShell
NIIT ISAS Q5 Report - Windows PowerShell
 

Similaire à PowerShell Formatting Deep Dive

Deep dive formatting
Deep dive formattingDeep dive formatting
Deep dive formattingThomas Lee
 
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGWORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGHitesh Mohapatra
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake TutorialFu Haiping
 
Mule data weave_10
Mule data weave_10Mule data weave_10
Mule data weave_10kunal vishe
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101Thomas Lee
 
Magento 2 | Declarative schema
Magento 2 | Declarative schemaMagento 2 | Declarative schema
Magento 2 | Declarative schemaKiel Pykett
 
OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL Suraj Bang
 
QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7Akash Tyagi
 
Free Based DSLs for Distributed Compute Engines
Free Based DSLs for Distributed Compute EnginesFree Based DSLs for Distributed Compute Engines
Free Based DSLs for Distributed Compute EnginesJoydeep Banik Roy
 
PowerShell crashcourse for Sharepoint admins
PowerShell crashcourse for Sharepoint adminsPowerShell crashcourse for Sharepoint admins
PowerShell crashcourse for Sharepoint adminsConcentrated Technology
 
Monitoring and Maintaining SharePoint 2013 Server
Monitoring and Maintaining SharePoint 2013 ServerMonitoring and Maintaining SharePoint 2013 Server
Monitoring and Maintaining SharePoint 2013 ServerLearning SharePoint
 
SQLS*Plus SQL Server command line tool
SQLS*Plus SQL Server command line toolSQLS*Plus SQL Server command line tool
SQLS*Plus SQL Server command line toolmemfix
 
Ruby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVCRuby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVCSimone Chiaretta
 

Similaire à PowerShell Formatting Deep Dive (20)

Deep dive formatting
Deep dive formattingDeep dive formatting
Deep dive formatting
 
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGWORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake Tutorial
 
Mule data weave_10
Mule data weave_10Mule data weave_10
Mule data weave_10
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101
 
Magento 2 | Declarative schema
Magento 2 | Declarative schemaMagento 2 | Declarative schema
Magento 2 | Declarative schema
 
OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL OWB11gR2 - Extending ETL
OWB11gR2 - Extending ETL
 
PowerShell-1
PowerShell-1PowerShell-1
PowerShell-1
 
QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7
 
Free Based DSLs for Distributed Compute Engines
Free Based DSLs for Distributed Compute EnginesFree Based DSLs for Distributed Compute Engines
Free Based DSLs for Distributed Compute Engines
 
Google cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache FlinkGoogle cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache Flink
 
Chapter09
Chapter09Chapter09
Chapter09
 
Test
TestTest
Test
 
PowerShell crashcourse for Sharepoint admins
PowerShell crashcourse for Sharepoint adminsPowerShell crashcourse for Sharepoint admins
PowerShell crashcourse for Sharepoint admins
 
Django crush course
Django crush course Django crush course
Django crush course
 
Monitoring and Maintaining SharePoint 2013 Server
Monitoring and Maintaining SharePoint 2013 ServerMonitoring and Maintaining SharePoint 2013 Server
Monitoring and Maintaining SharePoint 2013 Server
 
PowerShell crashcourse for sharepoint
PowerShell crashcourse for sharepointPowerShell crashcourse for sharepoint
PowerShell crashcourse for sharepoint
 
Zend Lab
Zend LabZend Lab
Zend Lab
 
SQLS*Plus SQL Server command line tool
SQLS*Plus SQL Server command line toolSQLS*Plus SQL Server command line tool
SQLS*Plus SQL Server command line tool
 
Ruby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVCRuby on Rails vs ASP.NET MVC
Ruby on Rails vs ASP.NET MVC
 

PowerShell Formatting Deep Dive

  • 1. MONTHLY WEBCAST Formatting with PowerShell Thomas Lee PowerShell MVP doctordns@gmail.com
  • 2. MONTHLY WEBCAST Agenda  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. MONTHLY WEBCAST Formatting 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. MONTHLY WEBCAST The Formatting Process  The default formatting process Cmdlet or Format-Table or Out-Default Pipeline Format-List Formatted Output On Console
  • 5. MONTHLY WEBCAST The Formatting Process  User Defined Formatting Cmdlet or Format-Table or Out-Default Pipeline Format-List Formatted Output On Console
  • 6. MONTHLY WEBCAST The Formatting Process  Other Options Out-Gridview Cmdlet or Pipeline Out-* Cmdlets Text, CSV, XML
  • 7. MONTHLY WEBCAST Format-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. MONTHLY WEBCAST Format-Wide  Used to print a single property as a table
  • 9. MONTHLY WEBCAST Format-* 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. MONTHLY WEBCAST Format-* 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. MONTHLY WEBCAST How 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. MONTHLY WEBCAST Format.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. MONTHLY WEBCAST Default 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. 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. MONTHLY WEBCAST Composite 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. 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. 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. MONTHLY WEBCAST Formatting 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. MONTHLY WEBCAST Hash 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. MONTHLY WEBCAST More 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. MONTHLY WEBCAST Other Output Mechanisms  XML  Import-CliXML  Export-CliXML  ConvertTo-XML  To a grid  Out-Gridview  CSV  Export-CSV (and Import-CSV)
  • 22. MONTHLY WEBCAST Out-GridView  Uses WPF  You need latest .NET Framework  Creates sortable list in a separate window with criteria to help limit output
  • 23. MONTHLY WEBCAST Out-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. MONTHLY WEBCAST Formatting 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. MONTHLY WEBCAST 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-FormatData to add new view  Add this to $profile to persist the changea
  • 26. MONTHLY WEBCAST 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-FormatData to add new view  Add this to $profile to persist the change
  • 27. MONTHLY WEBCAST 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?
  • 28. MONTHLY WEBCAST Create 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. 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. MONTHLY WEBCAST List Control <ListControl> <ListEntries> <ListEntry> <ListItems> <ListItem> <PropertyName>Model</PropertyName> </ListItem> … <ListItems> <ListEntry> </ListEntries> </Listcontrol>
  • 31. MONTHLY WEBCAST Combine 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. MONTHLY WEBCAST Using 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. MONTHLY WEBCAST Summary  Formatting can be simple or complex  Lots of alternatives – have it your way  Keep it simple and extend to meet your needs
  • 34. MONTHLY WEBCAST Adding To Your Profile  Possibly add some default format hash tables for commonly used outputs
  • 35. MONTHLY WEBCAST Resources  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