r/PowerShell • u/AardvarkNo8869 • Dec 06 '25
I HATE PSCustomObjects
Sorry, I just don't get it. They're an imbred version of the Hashtable. You can't access them via index notation, you can't work with them where identity matters because two PSCustomObjects have the same hashcodes, and every variable is a PSCustomObjects making type checking harder when working with PSCO's over Hashtables.
They also do this weird thing where they wrap around a literal value, so if you convert literal values from JSON, you have a situation where .GetType() on a number (or any literal value) shows up as a PSCustomObject rather than as Int32.
Literally what justifies their existence.
Implementation for table:
$a = @{one=1;two=2; three=3}
[String]$tableString = ""
[String]$indent = " "
[String]$seperator = "-"
$lengths = [System.Collections.ArrayList]@()
function Add-Element {
param (
[Parameter(Mandatory)]
[Array]$elements,
[String]$indent = " "
)
process {
for ($i=0; $i -lt $Lengths.Count; $i++) {
[String]$elem = $elements[$i]
[Int]$max = $lengths[$i]
[String]$whiteSpace = $indent + " " * ($max - $elem.Length)
$Script:tableString += $elem
$Script:tableString += $whiteSpace
}
}
}
$keys = [Object[]]$a.keys
$values = [Object[]]$a.values
for ($i=0; $i -lt $keys.Count; $i++) {
[String]$key = $keys[$i]
[String]$value = $values[$i]
$lengths.add([Math]::Max($key.Length, $value.Length)) | Out-Null
}
Add-Element $keys
$tableString+="`n"
for ($i=0; $i -lt $Lengths.Count; $i++) {
[Int]$max = $lengths[$i]
[String]$whiteSpace = $seperator * $max + $indent
$tableString += $whiteSpace
}
$tableString+="`n"
Add-Element $values
$tableString
$a = @{one=1;two=2; three=3}
[String]$tableString = ""
[String]$indent = " "
[String]$seperator = "-"
$lengths = [System.Collections.ArrayList]@()
function Add-Element {
param (
[Parameter(Mandatory)]
[Array]$elements,
[String]$indent = " "
)
process {
for ($i=0; $i -lt $Lengths.Count; $i++) {
[String]$elem = $elements[$i]
[Int]$max = $lengths[$i]
[String]$whiteSpace = $indent + " " * ($max - $elem.Length)
$Script:tableString += $elem
$Script:tableString += $whiteSpace
}
}
}
$keys = [Object[]]$a.keys
$values = [Object[]]$a.values
for ($i=0; $i -lt $keys.Count; $i++) {
[String]$key = $keys[$i]
[String]$value = $values[$i]
$lengths.add([Math]::Max($key.Length, $value.Length)) | Out-Null
}
Add-Element $keys
$tableString+="`n"
for ($i=0; $i -lt $Lengths.Count; $i++) {
[Int]$max = $lengths[$i]
[String]$whiteSpace = $seperator * $max + $indent
$tableString += $whiteSpace
}
$tableString+="`n"
Add-Element $values
$tableString
11
u/awit7317 Dec 06 '25
Their greatness. Their simplicity.
PowerShell didn’t always have classes.
Users of PowerShell didn’t necessarily come from an object oriented background.
7
u/lxnch50 Dec 06 '25
I think you just don't know how to use them. Hard to say why when you show no code.
3
u/sid351 Dec 06 '25
If you post some actual examples of things you're trying to achieve, rather than rants about
Get-Commandand empty "Test" posts, maybe we can help.With that said, I get the impression you don't really want help.
It would be wild of me to go to a python sub and yell at them that I hate the whitespace delineation. That is essentially what you've just done.
I think, but have not checked and verified, some of your problems could be resolved by defining the type of your variables and priorities in your custom objects.
Something like:
That's untested, written from memory, and written on mobile, so I could be wrong somewhere.
2
u/LongAnserShortAnser Dec 06 '25 edited Dec 06 '25
PSCustomObjects allow you to do much more than hashtables. Others have already touched on object formatting.
You can easily add type information to allow you to discern the type of object you are dealing with ...
Assuming you've already created an object called
$myObjfrom a hashtable and want to declare the type as "MyCustomObject":Alternatively, you can insert this directly into the hastable as you create the object:
But you can also enrich the object by adding methods in the form of a ScriptProperty. An example I saw recently was to return a file size in KB, MB or GB (rounded to 2 dec place) instead of raw bytes.
Have a look at the documentation for the
Add-MemberandUpdate-TypeDatacmdlets. Whilst you're at it, look at the documentation entry forabout_PSCustomObject... it discusses differences between using raw hastables or casting hashtables as PSCustomObjects using the type accelerator.Jeff Hicks (one of the best known PowerShell authors/instructors) has recently been writing articles touching on just these subjects.
(The articles are from subscription, but happy to forward the 3 relevant ones, if you DM me. He's definitely worth the cost of a sub if you are working with PowerShell a lot.)
Edit to add:
Objects are also much easier to deal with further along the pipeline ...
Functions can be written to accept parameters directly from the pipeline - either as an object itself, or by Property Name. This negates the need to
ForEach-Objectevery instance of a hastable or deal with an array of hashtables.2
u/Thotaz Dec 06 '25
Ok OP. Have fun with your hashtables when commands expect proper objects:
5
u/surfingoldelephant Dec 06 '25 edited Jun 10 '26
To address the specific points you've made:
That's right, because custom objects are dynamically created, anonymous property bags.
Non-array indexing requires a CLR type to implement its own indexer. This type of indexing is just syntactic sugar for calling
Item()(or whatever custom-name indexer) that's exposed in PowerShell as aParameterizedProperty.What scenarios would benefit from using
[]to access properties? Especially considering property names can only be strings.With dictionary keys,
[]enables fast lookups without explicitly needing to call the indexer. There are other tangible benefits too.But for properties specifically, why would you want to use
$obj['Prop']over$obj.Prop?Admittedly, the ability to slice would be nice, (i.e.,
$obj['P1', 'P2']), but I don't see this as particularly important and the following are all options:Valid criticism (see issue #15806).
But can you actually provide a concrete example of you encountering this issue?
Note that you can still use comparison operators to test for reference equality.
No, you're confusing objects with/without a
PSObjectwrapper. The[pscustomobject]type accelerator refers to the same underlying type as[psobject](both point to[Management.Automation.PSObject]). You need to use[Management.Automation.PSCustomObject]instead if you want to explicitly check for custom objects.You can also decorate objects with custom type names that allow you to target specific instances in formatting, parameter binding, etc.
If you want to check an object is "your" custom object:
Can you provide some code that demonstrates this? Are you sure
GetType()is involved?1
u/7ep3s Dec 08 '25
make sure to only pass the hash under the table so the oop police won't catch you
1
u/BlackV Dec 06 '25
insert <Y'all Got Any More Of That examples> meme
I dont think you're comparing apples to oranges
I use customs all day every day
IP scanner example
some random user report
Random bits of hardware inventory with formatting
er... apparently some covid reports at some point, maybe someones reddit post ?
Some file properties from another random reddit post
but again you give no real examples, so not really sure what you're trying to do
1
u/Kirsh1793 Dec 07 '25
Sure, there are a lot of common use cases fpr hashtables and PSCustomObjects. But there are distinctions. A hashtable is mainly a collection, still. Meanwhile, a PSCustomObject is an object. The PSCustomObject can be consumed by Cmdlets, which can then automatically assign the correct property value to the correct parameter. Have you never piped things to Export-Csv or something like that? Have you ever written a function and used the ValueFromPipelineByPropertyName attribute? This is where PSCustomObjects are handy. Of course, you can develop a module and use classes for this and then instantiate the common object. But if you're developing a new tool and try stuff out, just make a PSCustomObject and send that to the new tool. It will work just as well.
I do a lot of scripting to create reports. I combine data from multiple sources and the use the ImportExcel module to create .xlsx exports my customers can use for further processing. I query the data sets from each source and usually have a property on which I can join them. So, I create a hashtable with the join property as key for one data set, then loop over the other data set. In each iteration of the loop, I create a PSCustomObject that contains all the properties I want in the final report. After the loop I end up with a list of PSCustomObjects that I can pipe to Export-Excel. In this use case, the hashtable is a collection much more than an object. If I used hashtables as well where I'm using PSCustomObjects, Export-Excel wouldn't know how to handle it.
I also have some of my own modules that can be piped into one another. They mostly put out PSCustomObjects instead of actual objects, just because it's easier to do. If I don't pipe the output into another Cmdlet, I use the TypeNames property to show the output in a predefined way in the console.
I love hashtables. They're super handy for quick lookup (so much better than checking if something is in an array) or if you want to return a single output from a remote command. But as soon as you want to pipe things into each other or want a default view for console output for one of your Cmdlets, PSCustomObjects are the way to go - not a hashtable. If I have a loop or a function returning multiple values with the same properties, I'll return a list of PSCustomObjects - not a list of hashtables.