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

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.

comments powered by Disqus