How to write Custom Powershell Cmdlet - Part 3

In last two articles I have discussed how you can write a custom Powershell Cmdlet and then register it to start using it.

From basic use of your Cmdlet, it is ready to be used and you will get results. For example when I ran my samazon search Cmdlet for Cisco related books, I get following results.


Title         : Cisco ASA: All-in-One Firewall, IPS, and VPN Adaptive Security Appliance (Networkin
                g Technology)
ISBN          : 1587052091
Authors       : {Omar Santos, Jazib Frahim}
ASIN          : 1587052091
SalesRank     : 
SmallImage    : http://ecx.images-amazon.com/images/I/412mTvW3fkL._SL75_.jpg
MediumImage   : http://ecx.images-amazon.com/images/I/412mTvW3fkL._SL160_.jpg
LargeImage    : http://ecx.images-amazon.com/images/I/412mTvW3fkL.jpg
DetailsUrl    : 
ListPrice     : $80.00
AverageRating : 0

Title         : CCNA: Cisco Certified Network Associate Study Guide: Exam 640-802
ISBN          : 0470110082
Authors       : {Todd Lammle}
ASIN          : 0470110082
SalesRank     : 
SmallImage    : http://ecx.images-amazon.com/images/I/51BHKGcPzsL._SL75_.jpg
MediumImage   : http://ecx.images-amazon.com/images/I/51BHKGcPzsL._SL160_.jpg
LargeImage    : http://ecx.images-amazon.com/images/I/51BHKGcPzsL.jpg
DetailsUrl    : 
ListPrice     : $49.99
AverageRating : 0

You can see it served the purpose. This is basic view of output if you run Cmdlet. This is what is called list view of output. This is default output format.

Default output format

If you do not do anything extra at this point, Powershell will use default implementation of list format. It uses reflection on objects rendered by your Cmdlet and calls ToString() method on each public property and field in your object and renders it. And if you have some nested objects in your main object, you will notice that output will simply display fully qualified class names of those objects, unless you have overridden implementation of ToString() method for those objects.

Custom view for Cmdlet

This default output does not look very useful if you are looking for out in more of a tabular form or you want to restrict display of properties or format in certain way. That would mean you will have to find a mean to tell Powershell run time about your custom formatting. Powershell does provide a means for it. You will be writing your own Format file and then registering it with Powershell. I will discuss writing a very simple format file for our Amazon search Cmdlet. And in later article i will discuss some advanced topics on formatting.

Custom format file for Cmdlet

Here is how my simple custom format file for book search looks like.


<Configuration>
 <ViewDefinitions>
  <View>
	<Name>ByteBlocks.AmazonAPI.Book</Name>
  <ViewSelectedBy>
  <TypeName>ByteBlocks.AmazonAPI.Book</TypeName>
  </ViewSelectedBy>
  <TableControl>
	<TableHeaders>
		<TableColumnHeader>
			<Label>ISBN</Label>
			<Width>12</Width>
			<Alignment>right</Alignment>
		</TableColumnHeader>
		<TableColumnHeader>
			<Label>Title</Label>
			<Width>30</Width>
			<Alignment>left</Alignment>
		</TableColumnHeader>
		<TableColumnHeader>
			<Label>List Price</Label>
			<Width>10</Width>
			<Alignment>right</Alignment>
		</TableColumnHeader>
		<TableColumnHeader>
			<Label>Avg. Rating</Label>
			<Width>15</Width>
			<Alignment>right</Alignment>
		</TableColumnHeader>
   </TableHeaders>
   <TableRowEntries>
		<TableRowEntry>
			<TableColumnItems>
			 <TableColumnItem>
   			  <PropertyName>ISBN</PropertyName>
			 </TableColumnItem>
			 <TableColumnItem>
			  <PropertyName>Title</PropertyName>
			 </TableColumnItem>
			 <TableColumnItem>
			  <PropertyName>ListPrice</PropertyName>
			 </TableColumnItem>
			 <TableColumnItem>
			  <PropertyName>AverageRating</PropertyName>
			 </TableColumnItem>
			</TableColumnItems>
		</TableRowEntry>
	</TableRowEntries>
  </TableControl>
 </View>
<ViewDefinitions>
<Configuration>

Here is what you need to do to create a simple custom format file.

  • Create a file named {Yourassemblyname}.Format.ps1xml. For example for my sample Cmdlet the file name is AmazonPS.format.ps1xml
  • Add parent node named Configuration
  • Add child node ViewDefinitions. This will act as container node for all views for your Cmdlet
  • Add View node to ViewDefinitions node. This node will contain all the formatting information for output.
  • Add Name node to give a name to this view. You can choose some friendly name.
  • Next add ViewSelectedBy and then TypeName node to it. This TypeName node contains full qualified class name of object that this view will be used for rendering. When Powershell sees that it is to render object of this type, it will use formatting provided here.
  • Add a TableControl node to View parent node. This is telling that a table format is to be used for rendering out of object that was specified in TypeName node.
  • Now add TableHeaders node to provide information about headers that need to be rendered for columns. If you do not want to render any headers, skip this part. Otherwise, add TableColumnHeader node for each column that you want to display. In TableColumnHeader, you will add following nodes
    • Label: This is header text that will be used for the column
    • Width: How wide the column is going to be. If you do not specify width for any column, powershell will divide the width of your console between all columns. So for nice compact view, it is recommended that you do specify some reasonable width that will be sufficient to accomodate the data for that column.
    • Alignment: You can specify align of header text here. You can set it to Left, Right or Center.
  • After setting the column headers, add TableRowEntries node to TableControl parent node. This is the node where you will configure what properties or elements of your object are going to be displayed and how. Add TableRowEntry node to TableRowEntries. Then add TableColumnItems node which is parent container of all columns that are going to be displayed. For each element that you want to render, add TableColumnItem node now. There where you will enter name of the property that needs to be rendered in the column. For that to happen, add PropertyName node under TableColumnItem node. Enter name of the property that you want to display. For now we will keep it simple rendering. If you do not specify any special handling for the property, powershell framework will simply call ToString() method for your property and display the value. In next article I will discuss advanced formatting where you will see how you can do some complex processing to customize view of these properties.
  • Now just save your file.

Register your format file

Now only thing left is to register your custom format file with Powershell. Run the following command from Powershell command prompt.

update-FormatData -prependpath [formatFilelocaiton]

Now run your Cmdlet and see you will get a formatted output. Following example shows the output from the format file that I wrote and used as example in this article.


        ISBN Title                          List Price     Avg. Rating
        ---- -----                          ----------     -----------
  096383729X Beating Cancer with Nutriti...     $24.95               0
  0815340788 The Biology of Cancer HB          $160.00               0
  0738213187 Cancer on Five Dollars a Da...     $14.00               0
             Crazy Sexy Cancer Tips             $17.95               0
  0446696897 Dr. Patrick Walsh's Guide t...     $16.99               0
  1601451830 Cancer-Free: Your Guide to ...     $37.00               0
  0802131786 Tropic of Cancer                   $13.00               0
  0756628679 Foods to Fight Cancer: Esse...     $19.95               0
  0452290104 Cancer: 50 Essential Things...     $14.00               0
  1891434012 How to Fight Cancer & Win          $16.95               0

In next article I will discuss some more output rendering and how to write a help file fot your custom Cmdlet.

blog comments powered by Disqus
$1.99 Website Hosting- Go Daddy Proud Sponsor of Danica Patrick

Smart Phones Poll

What smart phone do you currently own?





Show Results

Month List

Powered by BlogEngine.NET 2.0.0.49
Theme by Naveen Kohli