1

I have an object with a set of properties (depth: 1). How to output the object as a string in a format like this:

{property1_name:property1_value} {property2_name:property2_value} {property3_name...

(the above is a single line, but property values can of course have newlines/carriage returns etc)

Let's assume I do not know the property names, they can change.

Thank you!

0

1 Answer 1

4

It'll actually depend on what object you're looking through. I tested this out on a csv, and it works decently, although you may want to do some minor formatting for a different type of object.

$csv |
    Get-Member |
    Where-Object {$_.MemberType -eq "NoteProperty"} |
    Select-Object -Property Name | 
    ForEach-Object {
        "{" + $_.Name + " : " + $csv.($_.Name) + "}"
    }

For example, depending on what you see when you do $csv | Get-Member, you may want to change NoteProperty to Property or something else. This should probably work though.

Note that you also have to change the name of the variable (currently $csv) in two places.

Sign up to request clarification or add additional context in comments.

5 Comments

Can I also just comment on how meta powershell is. I love how you can do $csv.$_ to retrieve a property by the property's name through a variable so casually.
If you replace -Property Name with -ExpandProperty Name, you can use $_ instead of $_.Name in the ForEach-Object.
@MaximeFranchot I've got a simple "flat" object mostly with string properties. Using your code example and changing NoteProperty to Property I'm able to get property names but not values. I obviously changed $csv to the right variable name.
@gms0ulman thank you, I will try that, perhaps it will fix the issue where I can see property names but not property values. Does it mean the code should become "{" + $_ + " : " + $csv.($_) + "}" ?
@Alex By if you can get the property, then once pipelined you should be able to use $_ as the reference to the property. Try without .Name first, then try with if the previous didn't work. I played around until everything worked, for example, by commenting out the last pipeline until the output of the previous looked exactly how I wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.