Custom type extensions

PowerShell types are already very useful, but sometimes you will need to extend them with additional properties, for example. You already know that this is possible to use the Add-Member cmdlet to extend each object. However, this approach does not scale well.

If you know the type that needs to be extended, you might want to consider using custom type extensions. As with format data in the previous section, you have the opportunity to override existing types by prepending your custom data and appending type extensions:

$typeDefinition = @'
<Types>
<Type>
<Name>System.IO.FileInfo</Name>
<Members>
<ScriptProperty>
<Name>Hash</Name>
<GetScriptBlock>Get-FileHash -Path $this.FullName</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
</Types>
'@

# Like Add-Member, you define which kinds of properties you want to extend your objects with
$typeDefinition | Out-File -FilePath .MyCustomType.ps1xml

Update-TypeData -PrependPath .MyCustomType.ps1xml

Observe in the following screenshot how the added ScriptProperty looks like when working with your object:

Every FileInfo object is now extended by ScriptProperty called Hash that executes a script block. Short as it is, you can easily verify this with Get-Member as well.

For each type you want to extend, a Type node has to exist as a child of the Types node. Underneath the Type node in the Members node, add each new member that is needed. If you recall Add-Member, the member types that were used can be used here as well.

Custom type extensions will also be reviewed when we talk about modules, as modules are a good place for type extensions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset