0

In Powershell, I can do the following with a list

$obj = New-Object System.Object    
foreach ($item in $list) {
       $obj | Add-Member -type NoteProperty -name fname -value $item.firstname
       $obj | Add-Member -type NoteProperty -name lname -value $item.lastname
    }

    $obj

and this will print out two columns with the first and last name.

In C#, i'm not sure how I can accomplish this. Do I need to create a custom class for each object? Or is there a way to do this dynamically in c# like in powershell?

The data i've got is in JSON. I can use JSON.net to iterate through the list of results but I'm not sure how to put them into an object such that

WriteObject(customObj);

will result in the same output as above.

By the way, this is all inside of a PSCmdlet class so output will always go to the console/cmd window.

thank you.

2 Answers 2

4

In C# you should operate on PSObject to achieve same result as your PowerShell code:

PSObject obj=new PSObject();
obj.Properties.Add(new PSNoteProperty(fname,item.firstname));
obj.Properties.Add(new PSNoteProperty(lname,item.lastname));
WriteObject(obj);
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry it took so long for me to verify your answer. I was only just able to get back to the task. I followed your suggestion along with ArrayList to produce a nice table of objects that can be easily used by PowerShell. Thanks again.
4

Your best option would be to use anonymous types. The code you gave would (probably) be equivalent to:

var obj = new List<dynamic>();
foreach (var item in list)
    obj.Add(new { fname = item.firstname, lname = item.lastname });
//From here, use whatever output method you would like.

To access the members, use obj[index].fname to get the fname at index, obj[index].lname to get the lname at index, obj.Select(item => item.fname) to get an IEnumerable<string> of all fnames, and obj.Select(item => item.lname) to get an IEnumerable<string> of all lnames.

Comments

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.