2

#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.

 

Filed in: Columns, Tips and Tricks Tags: ,

2 Responses to "#PSTip Convert PowerShell Data File to an Object"

  1. Mike P says:

    So how do I take a hashtable / PSObject and write it out to a PSD1 data file??

Leave a Reply

Submit Comment

© 2017 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: