pscustomobject add alias property

Hello,

I would like to know how to define an alias inside pscustomobject. ?

Sth like :

[pscustomobject]@{
   ComputerName = $_
   [Alias]HostName = ComputerName
}

I know that we can use Add-Member by :
$obj | Add-Member -MemberType AliasProperty -Name Hostname -Value ComputerName

But people told me that Add-Member is much slower that PsCustomObject, I would like know if we can declare Alias directly inside PsCustomObject ?

Thanks
Xiang

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

Hi Dave,

Thx a lot for your reply.

I tested your code, it works, but works for only one object.
for exemple:

$result = @()

$array | % {
$result += [pscustomobject]@{
    PSTypeName = $script:myTypeName
    ComputerName = 'SomeComputerName'
}
}

I got the error saying that :

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:

$array | % {
$result += [pscustomobject]@{
    ComputerName = 'SomeComputerName'
}
}

$result | Add-Member -MemberType AliasProperty -Name Hostname -Value ComputerName

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.

Thx again.