The other day I posted an article about custom properties which wrapped up with a look at Update-TypeData. The goal is not so much to make your scripts or modules easier to use, but rather to increase efficiency at the command prompt. When running commands interactively I want to get the information I need as easily as possible. In my PowerShell profile scripts I have code that defines a number of type extensions to make my life easier. I thought I'd share some of them with you.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
It seems I spend a lot of time working with files in PowerShell so I have code to add some type extensions to the System.IO.FileInfo object. For example, I prefer "Size" to "Length", so it is pretty simple to create an alias property.
Update-TypeData -TypeName System.IO.FileInfo -MemberType AliasProperty -MemberName Size -Value Length -force
But I have several alias properties, so I have a hashtable of aliases and their values that I pipe to Update-TypeData.
$aliases = @{ Size = "length" Modified = "LastWriteTime" Created = "CreationTime" } $aliases.GetEnumerator() | foreach { Update-TypeData -TypeName System.IO.FileInfo -MemberType AliasProperty -MemberName $_.key -Value $_.value -force }
With these additions I can run commands like this:
I used to have aliases like 'sz' for Length and 'lwt' for LastWriteTime when I was feeling especially lazy. But I decided that even that was too far.
I also have extensions for measurement objects. I used to have always run code like this:
dir c:\work -file | Measure-object -Property length -sum | Select Count,@{Name="SumKB";Expression={$_.sum/1kb}}
Again, I want something easier to type. In my profile I define script property type extensions for the measureinfo object.
Update-TypeData -TypeName Microsoft.PowerShell.Commands.GenericMeasureInfo -MemberType ScriptProperty -MemberName SumKB -Value {[math]::Round($this.sum/1KB,2)} -Force Update-TypeData -TypeName Microsoft.PowerShell.Commands.GenericMeasureInfo -MemberType ScriptProperty -MemberName SumMB -Value {[math]::Round($this.sum/1MB,2)} -Force Update-TypeData -TypeName Microsoft.PowerShell.Commands.GenericMeasureInfo -MemberType ScriptProperty -MemberName SumGB -Value {[math]::Round($this.sum/1GB,2)} -Force
If I don't specify a sum, the property values are 0.
But when I need the value it is there.
Which makes it much easier to write my PowerShell commands.
dir c:\scripts -file | group extension | Select Count,Name, @{Name="SizeKB";Expression={($_.group | Measure length -sum).sumkb}} | sort SizeKB -Descending | select -first 10
Again, these extensions are merely to make my life easier at the console. What makes your life easier?