Mark H
Mark H

Reputation: 31

How to make a PSCustomObject with Nested Values

I am trying to create a PSCustomObject with nested values and am having a really tough time, I see plenty of examples of hash tables and pscustom objects but for only extremely basic sets of data.

I am trying to create a a pscustom object that will have a server name property and then another property that has an array of services as well as their current running status.

I was able to make a hash table of the services and their running status but when I try to make an object with the has table it doesnt work very well:

hash table contains service names and their running status (stopped or running)

    $hashtable

    $myObject = [PSCustomObject]@{
    Name     = "$server"
    Services = "$hashtable"
    }

I am open to anything really, I have plenty of examples of how to convert items from JSON or XML and would love be able to use those as well but still having the same issue with being able to format the data in the first place.

edit: sorry about some of the vagueness of this post. As some people have already mentioned, the problem was the double qoutes around the hashtable. Everything is working now

Upvotes: 0

Views: 4813

Answers (1)

BenH
BenH

Reputation: 10044

As @t1meless noted in the comments, when you enclose a variable in double quotes it will attempt to convert that value to a string. For a Hashtable object, rather than give any information on from the object this will return "System.Collections.Hashtable". If you remove the double quotes, it will store the value of the hashtable as you are intending.

Here is a full example of what pulling the service information from a server and storing the values in a custom object. Note that $server can still be left in quotes as it is a string, but since it's already a string this would be unnecessary.

$myObject = Foreach ($Server in $Servers) {
    $hashtable = @{}
    Get-Service -ComputerName $Server | ForEach-Object { $hashtable.Add($_.name,$_.Status}

    [PSCustomObject]@{
        Name     = "$Server"
        Services = $hashtable
    }
}

Upvotes: 1

Related Questions