2

#PSTip Adding extended types – the PowerShell 3.0 way!

PowerShell 3.0 introduced important changes to the Update-TypeData cmdlet which includes specifying the dynamic type data. Using these new features of Update-TypeData cmdlet, we can add extended types without using the types.ps1xml files.

For example, let us say that we want to add the age of a file as a property to the output of Get-ChildItem cmdlet.

This can be achieved using:

Update-TypeData -TypeName System.IO.FileInfo -MemberName FileAge -MemberType ScriptProperty -Value { ((get-date) - ($this.creationtime)).days }

What we are doing in the above command is very straightforward. For every System.IO.FileInfo type of object, we instruct PowerShell to add a ScriptProperty called FileAge and assign the days since the file was created as its value.

FileAge ScriptProperty

In PowerShell 2.0, this would require creating a types.ps1xml file and then using Update-TypeData cmdlet. PowerShell 3.0 made it very simple and efficient to use. Make a note, however, the Update-TypeData does not update the format information for the specified types. It only applies to the current session and won’t be available once you close the session.

Filed in: Columns, Tips and Tricks Tags: , , ,

2 Responses to "#PSTip Adding extended types – the PowerShell 3.0 way!"

  1. Jens Kalski says:

    That’s a nice feature. It would be fine, if PS3 would be available for Windows 7 and 2008 R2. Nearby two months to wait is hard.

  2. Ravikanth says:

    We are all waiting too. Can’t wait to update all my lab machines to v3!

Leave a Reply

Submit Comment

© 9223 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: