+ All Categories
Home > Documents > Formatting With PowerShell

Formatting With PowerShell

Date post: 24-May-2015
Category:
Upload: thomas-lee
View: 1,259 times
Download: 1 times
Share this document with a friend
Description:
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.
Popular Tags:
36
MONTHLY WEBCAST Formatting with PowerShell Thomas Lee PowerShell MVP [email protected]
Transcript
Page 1: Formatting With PowerShell

MONTHLY WEBCAST

Formatting with PowerShell

Thomas Lee

PowerShell MVP

[email protected]

Page 2: Formatting With PowerShell

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

Page 3: Formatting With PowerShell

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

Page 4: Formatting With PowerShell

MONTHLY WEBCAST

The Formatting Process

The default formatting process

Cmdlet orPipeline Out-Default Format-Table or

Format-List

Formatted OutputOn Console

Page 5: Formatting With PowerShell

MONTHLY WEBCAST

The Formatting Process

User Defined Formatting

Cmdlet orPipeline

Format-Table orFormat-List Out-Default

Formatted OutputOn Console

Page 6: Formatting With PowerShell

MONTHLY WEBCAST

The Formatting Process

Other Options

Cmdlet orPipeline

Out-Gridview

Text, CSV, XML

Out-* Cmdlets

Page 7: Formatting With PowerShell

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

Page 8: Formatting With PowerShell

MONTHLY WEBCAST

Format-Wide

Used to print a single property as a table

Page 9: Formatting With PowerShell

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

Page 10: Formatting With PowerShell

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

Page 11: Formatting With PowerShell

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

Page 12: Formatting With PowerShell

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

Page 13: Formatting With PowerShell

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

Page 14: Formatting With PowerShell

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

Page 15: Formatting With PowerShell

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

Page 16: Formatting With PowerShell

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

Page 17: Formatting With PowerShell

MONTHLY WEBCAST

.NET Format Strings

Numeric format strings http://msdn.microsoft.com/en-us/library/427bttx3(VS.7

1).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

Page 18: Formatting With PowerShell

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

Page 19: Formatting With PowerShell

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

Page 20: Formatting With PowerShell

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

Page 21: Formatting With PowerShell

MONTHLY WEBCAST

Other Output Mechanisms

XML Import-CliXML Export-CliXML ConvertTo-XML

To a grid Out-Gridview

CSV Export-CSV (and Import-CSV)

Page 22: Formatting With PowerShell

MONTHLY WEBCAST

Out-GridView

Uses WPF You need latest .NET Framework

Creates sortable list in a separate window with criteria to help limit output

Page 23: Formatting With PowerShell

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

Page 24: Formatting With PowerShell

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

Page 25: Formatting With PowerShell

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

Page 26: Formatting With PowerShell

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

Page 27: Formatting With PowerShell

MONTHLY WEBCAST

Create a Class Using Add-TypeAdd-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?

Page 28: Formatting With PowerShell

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.

Page 29: Formatting With PowerShell

MONTHLY WEBCAST

TableControl

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

Page 30: Formatting With PowerShell

MONTHLY WEBCAST

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

Page 31: Formatting With PowerShell

MONTHLY WEBCAST

Combine It Together

Save XML to c:\foo\aeroplane.format.ps1xml Update-FormatData –Prepend c:\foo\

aeroplane.format.ps1xml

Then: $AP = new-object aeroplane $AP $AP | fl

Page 32: Formatting With PowerShell

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>

Page 33: Formatting With PowerShell

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

Page 34: Formatting With PowerShell

MONTHLY WEBCAST

Adding To Your Profile

Possibly add some default format hash tables for commonly used outputs

Page 35: Formatting With PowerShell

MONTHLY WEBCAST

Resources

Formatting - see my articles on formatting http://tfl09.blogspot.com/2010/02/formatting-w

ith-powershell.html

.NET Formatting http

://msdn.microsoft.com/en-us/library/txafckwd(VS.71).aspx

Page 36: Formatting With PowerShell

MONTHLY WEBCAST

Questions

?? ?? ??


Recommended