PowerShell-Technique: Update-TypeData

Created March 28, 2023

Enhancing PowerShell objects with Update-TypeData

Sometimes the objects that PowerShell cmdlets return don't have all the properties and methods that you need.

Fortunately, PowerShell provides a way to extend these objects using a feature called extended type data (ETD). ETD lets you add, remove, or modify properties and methods of a type, such as a .NET class or a PowerShell object.

One way to add new properties to PowerShell objects is by using the Update-TypeData cmdlet. Here's an example that shows how to add a new property to every System.IO.DirectoryInfo object returned by the Get-ChildItem cmdlet:

$agedFiveDaysScript = {
    if ((Get-ChildItem -Path $this.FullName).CreationTime -lt (Get-Date).AddDays(-5)) {
        $true
    } else {
        $false
    }
}

$etd = @{
    TypeName = 'System.IO.DirectoryInfo'
    MemberType = 'ScriptProperty'
    MemberName = 'AgedFiveDays'
    Value = $agedFiveDaysScript
}

Update-TypeData @etd

Get-ChildItem -Path 'C:\Temp' -Directory | Select-Object FullName, AgedFiveDays

In this example, a new script property called AgedFiveDays is added to the System.IO.DirectoryInfo type using ETD. The AgedFiveDays property returns $true if the directory contains any items that were created more than 5 days ago, or $false if all items were created less than 5 days ago. This could be useful for finding old directories in a file share for cleanup, for example.

Note that the assignment of the ETD definition only exists in the current PowerShell session and will affect every object of the defined type created afterwards. This means that it could cause compatibility issues with other cmdlets or functions that return objects of the same type.

Alternatively, you can pipe a cmdlet directly to the Update-TypeData command, without using a variable. However, be aware that the returned object could contain other types in addition to the expected one, like Get-ChildItem.

Get-Process | Update-TypeData -TypeName System.Diagnostics.Process -MemberType NoteProperty -MemberName MyCustomProperty -Value 'Hello, world!'

Get-Process | Select-Object -First 1 | ForEach-Object {
    Write-Host "Process ID: $($_.Id)"
    Write-Host "Process name: $($_.ProcessName)"
    Write-Host "My custom property value: $($_.MyCustomProperty)"
}

In this example, a new note property called MyCustomProperty is added to the System.Diagnostics.Process type. The MyCustomProperty property is not defined by default, so we add it using ETD with a simple string value. Then, we use Select-Object and ForEach-Object to show the value of the new property for the first process returned by Get-Process cmdlet.

ETD can be a powerful tool for modifying and enhancing objects in PowerShell, but use it with caution to avoid compatibility issues.

Thats all for now.

If you have any thoughts or feedback on this topic, feel free to share them with me on Twitter at Christian Ritter. Best regards,

Christian.