You can give your object a custom TypeName, and then use Update-TypeData to add the alias property to all objects of that type, instead of having to do it every time you create the objects. (You can also create a types.ps1xml file that is distributed with your module and automatically loaded, rather than relying on Update-TypeData.) For example:
# When my module is imported, run some init code to set up the type data:
$script:myTypeName = 'Dave.Demo'
Update-TypeData -TypeName $script:myTypeName -MemberType AliasProperty -MemberName HostName -Value ComputerName
# In my function that creates the objects:
[pscustomobject]@{
PSTypeName = $script:myTypeName
ComputerName = 'SomeComputerName'
}
<#
Notice the output:
ComputerName HostName
------------ --------
SomeComputerName SomeComputerName
#>
Update-TypeData : Error in TypeData "Dave.Demo" : The member HostName is already persent.
After that I found another solution. It was my fault that I didn’t test Add-Member before, I thought it could only work with “New-Object -TypeName PSObject”, which is very slow :
But in fact Add-Member can also cooperate with PsCustomObject, the code is like as follows:
As Add-Member is used only once, I suppose it won’t degrade the performance.
The key point is that we must use Add-Member at the end of the generation of $result.
If we use it inside the ForEach-Object loop, we will get the similar error like above saying that Hostname is alreay present.
For your TypeName method, maybe we can do similar thing to get it worked : declare the alias in the end. But I haven’t figured it out yet.