SlideShare a Scribd company logo
How Do They Do That?
Formatting with PowerShell
Thomas Lee
Agenda
•   Review the basics
•   Composite Formatting and .ToString
•   Formatting with Format-tables
•   Using Format XML
•   EasyOutput (thanks James!)

• DEMOS!!
Who Am I
• Consultant/writer/trainer – living in the UK
• Long time PowerShell MVP
• 2 blogs
  – http://tfl09.blogspot.com – Under The Stairs
  – http://pshscripts.blogspot.com – PowerShell
    Scripts Blog
Formatting by Default
• PowerShell formats output by default
  – controlled by *.PS1XML files
  – Some default rules if all else fails
• 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
Formatting Rules
• If format.ps1xml defines format for a type
  – Use that
• If not, does type.ps1xml define a default
  property set
  – Use that and the rules below
• Otherwise table vs list rules
  – 4 or less properties, output a table
  – 5 or more output a list
Format-Table and Format-List
 Format-List/Format-Table take objects from
  pipeline
   Formats those objects
 Default contents and ‘shape’ from .ps1xml
 You can override default properties
   GWMI win32_ComputerSystem | fl name,model

 Can also take a hash table for precise format
  control
Occurrence Type Drives Formatting
• An object’s type determine how PowerShell
  renders instances
• .PS1XML defines the format for many types
  – Others use the last resort rules (1-4/5+)
Other Stuff I Assume You Know
• Format-Wide and what it’s good for
• The basic Format-Table and Format-List
  cmdlets
• The –autosize parameter on Format-Table
  – And the implications for larger result sets
• Out-GridView
• Other Output mechanisms (XML, CSV, etc.3)
Demo 1

REVIEWING THE BASICS
Formatting Strings
• You can use either
  – -f operator, and format values into a composite
    formatting string
     “This is {0}, formatting with {1}” –f “fun” , ”PowerShell”

   – Use .ToString() to format a single value
Composite Formatting String
• Format of anchor
  – {<number, width:formatspecifier>}
  – Eg {0, 10: n4}
• Formatting
  <string with anchors> -f <array of values>
     • Produces a formatted string of array values
     • $date=get-date
     • “Today, {0}, is {1}” –f $date.date, $date.dayofweek
.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 format string in call to .ToString()
   $i = 23.123456; $i.tostring("N2")
   23.12
.NET Format String Reference
 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
Demo 2

FORMATTING STRINGS/.TOSTRING()
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
Hash Table Example
$Pn=@{label="Process Name";
       Expression={$_.Name};
       Alignment="right"}

$Cpu=@{label="CPU Cost";
       Expression={($_.CPU) * 21;.23};
       FormatString=“C3"}

Get-Process notepad| Format-Table $Pn,$Cpu -auto
Demo 3

FORMAT-TABLE WITH HASH TABLES
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
Format driven by object's type
• Discover a variable’s type name(s)
  – $variable.PSTYPENAMES


• To add a type name
  – $variable.PSTYPENAMES.ADD(“new name”)


• To clear all type names
  – $variable.PSTYPENAMES.CLEAR()
Formatting XML
 To change how PowerShell formats a type?
   Create XML file
   Define views: table, list , etc
   Run Update-FormatData to add new view


 Add this to $profile to persist the changes
XML – Overall Structure
 <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.
Consider A New 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?
XML File Structure
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
  <ViewDefinitions>
      <View>
         <Name>   …   </Name>
         <ViewSelectedBy> <TypeName> … </TypeName>   </ViewSelectedBy>

         <TableControl> …   </TableControl>
         <ListControl> …    </ListControl>

  </ViewDefinitions>
</Configuration>
TableControl Definition
<TableControl>
  <TableHeaders>
      <TableColumnHeader>
         <label>Passengers Carried</label><width>20</width>
      </TableColumnHeader>    …
  </TableHeaders>
 <TableRowEntries>
      <TableRowEntry>
         <tableColumnItem><PropertyName>Pax</PropertyName></tablecolumnitem>
       </TableRowEntry>    …
    </TableRowEntries>
</TableControl>
ListControl
<ListControl>
    <ListEntries>
        <ListEntry>
            <ListItems>
                <ListItem>
                    <PropertyName>Model</PropertyName>
                </ListItem>     …
            <ListItems>
        <ListEntry>
    </ListEntries>
</Listcontrol>
Sticking It Together
 Author, then save XML
 Prior to use, update format data
  Update-FormatData –Prepend <format file name>



• Consider this pattern of development
  –   PowerShell
  –   PowerShell
  –   Test stuff and find bugs
  –   Exit
  –   Edit the XML
  –   PowerShell
  –   Do it again
Demo 4

DISPLAY XML
But wait
 Building XML is hard, boring, and just plain
  work
 Instead of DIY

 Easy out
 Great add on module
Demo 5

EASY OUT
Summary
 Formatting can be simple or complex
 Lots of alternatives – have it your way
 Keep it simple and extend to meet your needs
 Use EZ-out if you are accessing obscure WMI
  classes or using uncommon .NET types
• Demo 5

More Related Content

What's hot

Introduction to MySQL in PHP
Introduction to MySQL in PHPIntroduction to MySQL in PHP
Introduction to MySQL in PHPhamsa nandhini
 
Creating a database
Creating a databaseCreating a database
Creating a databaseRahul Gupta
 
Database Systems - SQL - DCL Statements (Chapter 3/4)
Database Systems - SQL - DCL Statements (Chapter 3/4)Database Systems - SQL - DCL Statements (Chapter 3/4)
Database Systems - SQL - DCL Statements (Chapter 3/4)Vidyasagar Mundroy
 
Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)  Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL) MuhammadWaheed44
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL CommandsShrija Madhu
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands1keydata
 
Advanced SQL Webinar
Advanced SQL WebinarAdvanced SQL Webinar
Advanced SQL WebinarRam Kedem
 
Obtain better data accuracy using reference tables
Obtain better data accuracy using reference tablesObtain better data accuracy using reference tables
Obtain better data accuracy using reference tablesKiran Venna
 
SQL Fundamentals - Lecture 2
SQL Fundamentals - Lecture 2SQL Fundamentals - Lecture 2
SQL Fundamentals - Lecture 2MuhammadWaheed44
 
SQL: Structured Query Language
SQL: Structured Query LanguageSQL: Structured Query Language
SQL: Structured Query LanguageRohit Bisht
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with examplepranav kumar verma
 
Oracle SQL Fundamentals - Lecture 3
Oracle SQL Fundamentals - Lecture 3Oracle SQL Fundamentals - Lecture 3
Oracle SQL Fundamentals - Lecture 3MuhammadWaheed44
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptgourav kottawar
 

What's hot (19)

Introduction to MySQL in PHP
Introduction to MySQL in PHPIntroduction to MySQL in PHP
Introduction to MySQL in PHP
 
Creating a database
Creating a databaseCreating a database
Creating a database
 
Database Systems - SQL - DCL Statements (Chapter 3/4)
Database Systems - SQL - DCL Statements (Chapter 3/4)Database Systems - SQL - DCL Statements (Chapter 3/4)
Database Systems - SQL - DCL Statements (Chapter 3/4)
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
 
SQL commands
SQL commandsSQL commands
SQL commands
 
Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)  Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
SQL
SQLSQL
SQL
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Advanced SQL Webinar
Advanced SQL WebinarAdvanced SQL Webinar
Advanced SQL Webinar
 
Obtain better data accuracy using reference tables
Obtain better data accuracy using reference tablesObtain better data accuracy using reference tables
Obtain better data accuracy using reference tables
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
 
SQL Fundamentals - Lecture 2
SQL Fundamentals - Lecture 2SQL Fundamentals - Lecture 2
SQL Fundamentals - Lecture 2
 
SQL: Structured Query Language
SQL: Structured Query LanguageSQL: Structured Query Language
SQL: Structured Query Language
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
 
Oracle SQL Fundamentals - Lecture 3
Oracle SQL Fundamentals - Lecture 3Oracle SQL Fundamentals - Lecture 3
Oracle SQL Fundamentals - Lecture 3
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
 

Similar to Deep dive formatting

Formatting With PowerShell
Formatting With PowerShell Formatting With PowerShell
Formatting With PowerShell Thomas Lee
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slidesmetsarin
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeClay Helberg
 
Powershell Training
Powershell TrainingPowershell Training
Powershell TrainingFahad Noaman
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101Thomas Lee
 
Querying XML: XPath and XQuery
Querying XML: XPath and XQueryQuerying XML: XPath and XQuery
Querying XML: XPath and XQueryKatrien Verbert
 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3Belal Arfa
 
QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7Akash Tyagi
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2Neeraj Mathur
 
Demystifying PostgreSQL (Zendcon 2010)
Demystifying PostgreSQL (Zendcon 2010)Demystifying PostgreSQL (Zendcon 2010)
Demystifying PostgreSQL (Zendcon 2010)NOLOH LLC.
 
Demystifying PostgreSQL
Demystifying PostgreSQLDemystifying PostgreSQL
Demystifying PostgreSQLNOLOH LLC.
 
eXtensible Markup Language (XML)
eXtensible Markup Language (XML)eXtensible Markup Language (XML)
eXtensible Markup Language (XML)Serhii Kartashov
 
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)Alexandre Rafalovitch
 
Unit2_XML_S_SS_US Data_CS19414.pptx
Unit2_XML_S_SS_US Data_CS19414.pptxUnit2_XML_S_SS_US Data_CS19414.pptx
Unit2_XML_S_SS_US Data_CS19414.pptxNEHARAJPUT239591
 
PowerShell Core Skills (TechMentor Fall 2011)
PowerShell Core Skills (TechMentor Fall 2011)PowerShell Core Skills (TechMentor Fall 2011)
PowerShell Core Skills (TechMentor Fall 2011)Concentrated Technology
 

Similar to Deep dive formatting (20)

Formatting With PowerShell
Formatting With PowerShell Formatting With PowerShell
Formatting With PowerShell
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data Merge
 
Powershell Training
Powershell TrainingPowershell Training
Powershell Training
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101
 
Querying XML: XPath and XQuery
Querying XML: XPath and XQueryQuerying XML: XPath and XQuery
Querying XML: XPath and XQuery
 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3
 
QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7
 
Developing a new Epsilon EMC driver
Developing a new Epsilon EMC driverDeveloping a new Epsilon EMC driver
Developing a new Epsilon EMC driver
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 
Demystifying PostgreSQL (Zendcon 2010)
Demystifying PostgreSQL (Zendcon 2010)Demystifying PostgreSQL (Zendcon 2010)
Demystifying PostgreSQL (Zendcon 2010)
 
Apache TAJO
Apache TAJOApache TAJO
Apache TAJO
 
Demystifying PostgreSQL
Demystifying PostgreSQLDemystifying PostgreSQL
Demystifying PostgreSQL
 
eXtensible Markup Language (XML)
eXtensible Markup Language (XML)eXtensible Markup Language (XML)
eXtensible Markup Language (XML)
 
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
Rebuilding Solr 6 examples - layer by layer (LuceneSolrRevolution 2016)
 
Unit2_XML_S_SS_US Data_CS19414.pptx
Unit2_XML_S_SS_US Data_CS19414.pptxUnit2_XML_S_SS_US Data_CS19414.pptx
Unit2_XML_S_SS_US Data_CS19414.pptx
 
Basics of XML
Basics of XMLBasics of XML
Basics of XML
 
Xml session
Xml sessionXml session
Xml session
 
PowerShell Core Skills (TechMentor Fall 2011)
PowerShell Core Skills (TechMentor Fall 2011)PowerShell Core Skills (TechMentor Fall 2011)
PowerShell Core Skills (TechMentor Fall 2011)
 
1 xml fundamentals
1 xml fundamentals1 xml fundamentals
1 xml fundamentals
 

More from Thomas Lee

PowerShell 101 - What is it and Why should YOU Care!
PowerShell 101 - What is it and Why should YOU Care!PowerShell 101 - What is it and Why should YOU Care!
PowerShell 101 - What is it and Why should YOU Care!Thomas Lee
 
Doing Azure With PowerShell
Doing Azure With PowerShellDoing Azure With PowerShell
Doing Azure With PowerShellThomas Lee
 
2016 spice world_london_breakout
2016 spice world_london_breakout2016 spice world_london_breakout
2016 spice world_london_breakoutThomas 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
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101Thomas Lee
 
2014 SpiceWorld London Breakout
2014 SpiceWorld London Breakout2014 SpiceWorld London Breakout
2014 SpiceWorld 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
 
Coping with Murphy’s Law
Coping with Murphy’s LawCoping with Murphy’s Law
Coping with Murphy’s LawThomas Lee
 

More from Thomas Lee (9)

PowerShell 101 - What is it and Why should YOU Care!
PowerShell 101 - What is it and Why should YOU Care!PowerShell 101 - What is it and Why should YOU Care!
PowerShell 101 - What is it and Why should YOU Care!
 
Doing Azure With PowerShell
Doing Azure With PowerShellDoing Azure With PowerShell
Doing Azure With PowerShell
 
2016 spice world_london_breakout
2016 spice world_london_breakout2016 spice world_london_breakout
2016 spice world_london_breakout
 
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!
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101
 
2014 SpiceWorld London Breakout
2014 SpiceWorld London Breakout2014 SpiceWorld London Breakout
2014 SpiceWorld 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
 
Coping with Murphy’s Law
Coping with Murphy’s LawCoping with Murphy’s Law
Coping with Murphy’s Law
 

Recently uploaded

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Thierry Lestable
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationZilliz
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaRTTS
 

Recently uploaded (20)

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 

Deep dive formatting

  • 1. How Do They Do That? Formatting with PowerShell Thomas Lee
  • 2. Agenda • Review the basics • Composite Formatting and .ToString • Formatting with Format-tables • Using Format XML • EasyOutput (thanks James!) • DEMOS!!
  • 3. Who Am I • Consultant/writer/trainer – living in the UK • Long time PowerShell MVP • 2 blogs – http://tfl09.blogspot.com – Under The Stairs – http://pshscripts.blogspot.com – PowerShell Scripts Blog
  • 4. Formatting by Default • PowerShell formats output by default – controlled by *.PS1XML files – Some default rules if all else fails • 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
  • 5. Formatting Rules • If format.ps1xml defines format for a type – Use that • If not, does type.ps1xml define a default property set – Use that and the rules below • Otherwise table vs list rules – 4 or less properties, output a table – 5 or more output a list
  • 6. Format-Table and Format-List  Format-List/Format-Table take objects from pipeline  Formats those objects  Default contents and ‘shape’ from .ps1xml  You can override default properties  GWMI win32_ComputerSystem | fl name,model  Can also take a hash table for precise format control
  • 7. Occurrence Type Drives Formatting • An object’s type determine how PowerShell renders instances • .PS1XML defines the format for many types – Others use the last resort rules (1-4/5+)
  • 8. Other Stuff I Assume You Know • Format-Wide and what it’s good for • The basic Format-Table and Format-List cmdlets • The –autosize parameter on Format-Table – And the implications for larger result sets • Out-GridView • Other Output mechanisms (XML, CSV, etc.3)
  • 10. Formatting Strings • You can use either – -f operator, and format values into a composite formatting string “This is {0}, formatting with {1}” –f “fun” , ”PowerShell” – Use .ToString() to format a single value
  • 11. Composite Formatting String • Format of anchor – {<number, width:formatspecifier>} – Eg {0, 10: n4} • Formatting <string with anchors> -f <array of values> • Produces a formatted string of array values • $date=get-date • “Today, {0}, is {1}” –f $date.date, $date.dayofweek
  • 12. .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 format string in call to .ToString()  $i = 23.123456; $i.tostring("N2")  23.12
  • 13. .NET Format String Reference  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
  • 15. 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
  • 16. Hash Table Example $Pn=@{label="Process Name"; Expression={$_.Name}; Alignment="right"} $Cpu=@{label="CPU Cost"; Expression={($_.CPU) * 21;.23}; FormatString=“C3"} Get-Process notepad| Format-Table $Pn,$Cpu -auto
  • 18. 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
  • 19. Format driven by object's type • Discover a variable’s type name(s) – $variable.PSTYPENAMES • To add a type name – $variable.PSTYPENAMES.ADD(“new name”) • To clear all type names – $variable.PSTYPENAMES.CLEAR()
  • 20. Formatting XML  To change how PowerShell formats a type?  Create XML file  Define views: table, list , etc  Run Update-FormatData to add new view  Add this to $profile to persist the changes
  • 21. XML – Overall Structure  <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.
  • 22. Consider A New 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?
  • 23. XML File Structure <?xml version="1.0" encoding="utf-8" ?> <Configuration> <ViewDefinitions> <View> <Name> … </Name> <ViewSelectedBy> <TypeName> … </TypeName> </ViewSelectedBy> <TableControl> … </TableControl> <ListControl> … </ListControl> </ViewDefinitions> </Configuration>
  • 24. TableControl Definition <TableControl> <TableHeaders> <TableColumnHeader> <label>Passengers Carried</label><width>20</width> </TableColumnHeader> … </TableHeaders> <TableRowEntries> <TableRowEntry> <tableColumnItem><PropertyName>Pax</PropertyName></tablecolumnitem> </TableRowEntry> … </TableRowEntries> </TableControl>
  • 25. ListControl <ListControl> <ListEntries> <ListEntry> <ListItems> <ListItem> <PropertyName>Model</PropertyName> </ListItem> … <ListItems> <ListEntry> </ListEntries> </Listcontrol>
  • 26. Sticking It Together  Author, then save XML  Prior to use, update format data Update-FormatData –Prepend <format file name> • Consider this pattern of development – PowerShell – PowerShell – Test stuff and find bugs – Exit – Edit the XML – PowerShell – Do it again
  • 28. But wait  Building XML is hard, boring, and just plain work  Instead of DIY  Easy out  Great add on module
  • 30. Summary  Formatting can be simple or complex  Lots of alternatives – have it your way  Keep it simple and extend to meet your needs  Use EZ-out if you are accessing obscure WMI classes or using uncommon .NET types • Demo 5