#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.

About the author: Ravikanth C

Ravikanth is the founder and editor of the PowerShell Magazine. He is also a PowerShell MVP who works at Dell Inc. He blogs at http://www.ravichaganti.com/blog and you can follow him on Twitter @ravikanth.

Related Posts

%d bloggers like this: