Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PSCustomObject to Hashtable

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?

like image 701
alphadev Avatar asked Sep 18 '10 02:09

alphadev


People also ask

Is a PSCustomObject a Hashtable?

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.

What is PSCustomObject?

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.

How do I create a hash table in PowerShell?

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.

How do I create a PSCustomObject in PowerShell?

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.


1 Answers

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 } 
like image 106
Keith Hill Avatar answered Sep 20 '22 18:09

Keith Hill