Hi,
I’ve created a PSCustomObject by doing the following
$productList = foreach ($p in 1..5)
{
[PSCustomObject]@{
SerialNumber = "CND$(Get-Random -Minimum 100 -Maximum 999)W$(Get-Random -Maximum 9)M"
PartNumber = "D$(Get-Random -Maximum 5)H$(Get-Random -Minimum 10 -Maximum 99)AV"
}
}
As far as I am aware I am supposed to be able to now see my properties if I go
$productList.psobject.properties.name
or access it by doing like
$productList.psobject.Properties['SerialNumber']
.
I only see the following properties if I select all the names
Count
Length
LongLength
Rank
SyncRoot
IsReadOnly
IsFixedSize
IsSynchronized
And I get nothing back when I try to access it.
I can do
PS C:\WINDOWS\system32> $productList | Get-Member -MemberType NoteProperty, Properties
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
PartNumber NoteProperty string PartNumber=D1H57AV
SerialNumber NoteProperty string SerialNumber=CND254W2M
and I can see the property being listed there and all is fine.
I am curious to why it does not work via psobject, anyone can help to explain it to me?
Thanks in advance,
//Tony
It’s because you are requesting the properties of the array of PSCustomObjects that you created and not the properties of an object in that array.
PS E:\> $productList = foreach ($p in 1..5)
>> {
>> [PSCustomObject]@{
>> SerialNumber = "CND$(Get-Random -Minimum 100 -Maximum 999)W$(Get-Random -Maximum 9)M"
>> PartNumber = "D$(Get-Random -Maximum 5)H$(Get-Random -Minimum 10 -Maximum 99)AV"
>> }
>> }
PS E:\> $productList.psobject.properties.name
Count
Length
LongLength
Rank
SyncRoot
IsReadOnly
IsFixedSize
IsSynchronized
PS E:\> $productList[0].psobject.properties.name
SerialNumber
PartNumber
PS E:\>
So the “.PSObject” part of the statement is actually referencing the Object and not the PSCustomObject that you created.
PS E:\> $productlist.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
When you put Get-Member in the pipeline, it is executing for each object that is passed to it, which would be each individual PSCustomObject in the array you created. That’s why it shows you the PSCust
omObject type and the custom properties you set.
Thank you sir!
Not sure how I could’ve missed it. It is now so obvious when you pointed it out.
Best regards