Skip to content

Create a PowerShell Object from contents of a file

No doubt you already use PowerShell for a wide range of tasks and consequently are already familiar working with PowerShell objects?

PowerShell is a task automation and configuration management framework from Microsoft

This post explains how to turn the contents of a file into a PowerShell object. You can then use this object for whatever you need. Say you have a file in C:\data\ with the content:

os=Windows 2012R2

Now you create a PowerShell function that will take the above content and split into a key:value set of data. If the file is delimited by a character other than “=” then just change it in the code below:

function Get-Details {
$properties = @{}
Get-Content $ENV:SYSTEMDRIVE\data\serverdetails | ForEach-Object {
$property = $_ -Split "=", 2
$properties.Add($property[0], $property[1])
return $properties

Run Get-Detailsto retrieve the entire object or if you rather put the object in a variable run: $details = Get-Details

If you have the object in a variable it makes it easier to retrieve specific values, for example you could use the below bit of code to print the hostname and city if it’s active:

if ($ -eq "yes") {
  Write-Output "$details.hostname is active in $"

The possibilities are endless, certainly this has given enough of an insight to spark your imagination ?

Finally check out my other similar blog post:
Using jq in Bash to manage JSON content

Published inMicrosoft

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.