What is the easiest way to convert a PSCustomObject
to a Hashtable
? It displays just like one with the splat operator, curly braces and what appear to be key value pairs. When I try to cast it to [Hashtable]
it doesn't work. I also tried .toString()
and the assigned variable says its a string but displays nothing - any ideas?
Objects are a collection of data representing an item and have data types like the object type, methods, and properties. PSCustomObjects differ from hash tables in that the object represents an entity.
Long description. The [pscustomobject] type accelerator was added in PowerShell 4.0. Prior to adding this type accelerator, creating an object with member properties and values was more complicated. Originally, you had to use New-Object to create the object and Add-Member to add properties.
To create a hash table in PowerShell, you'll use an @ symbol followed by an opening curly brace and a closing curly brace as shown below. Here you can see my hash table is now three lines with a key/value pair in the middle. It can also be represented on one line as well.
Creating a PSCustomObject in PowerShell You can also use the New-Object -TypeName PSObject -Property @{} which will work in earlier versions of PowerShell, but it is also slower. This speed comes into play when you need to create or manipulate many objects in a script.
Shouldn't be too hard. Something like this should do the trick:
# Create a PSCustomObject (ironically using a hashtable) $ht1 = @{ A = 'a'; B = 'b'; DateTime = Get-Date } $theObject = new-object psobject -Property $ht1 # Convert the PSCustomObject back to a hashtable $ht2 = @{} $theObject.psobject.properties | Foreach { $ht2[$_.Name] = $_.Value }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With