#PSTip Convert PowerShell Data File to an Object

Note: This tip requires PowerShell 4.0 or later.

Before PowerShell 4.0, if we had to convert the hash table in a PSD1 file into an object representation, we either used the Import-LocalizedData cmdlet (not really meant for this purpose) or other means. For example, June Blender tweeted one such method.

The Invoke-Expression cmdlet can be evil if you don’t know what’s inside the hash table string and can cause serious security issues. There are of course other methods such as a method I used in my PSBookmark module. I just put the hash table string in a .PS1 file and dot-source the PS1 to create an object. However, there are other better ways to achieve this.

Using Argument Transformation

With PowerShell 4.0 we don’t need all these. For PowerShell DSC, Microsoft introduced a new attribute called ArgumentToConfigurationDataTransformation. This is used when compiling a DSC configuration. Here is how I use it.

The beauty of this method is that you can supply a .PSD1 file path and the contents (valid hash table string) gets transformed into an object.

Using AST

Converting a hashtable string to an object can be done using AST as well. The following code snippet shows that.

Finally, using the Import-PowerShellDataFile cmdlet

In PowerShell 5.0, there is a new cmdlet called Import-PowerShellDataFile which wraps the AST way of generating an object from the hashtable string.


About the author: Ravikanth C

Ravikanth is the founder and editor of the PowerShell Magazine. He is also a PowerShell MVP who works at Dell Inc. He blogs at http://www.ravichaganti.com/blog and you can follow him on Twitter @ravikanth.

Related Posts