0

How do I take my Powershell object output and turn into c# object? I'm trying to get freespace info on remote drives and found this SO thread I'd like to use: How to get value from powershell script into C# variable?

Maybe transform into following:

class MyCSharpObject
{
    public string Name { get; set; }
    public string Used { get; set; }
    public string Free { get; set; }
}

Input:

using System.Collections.ObjectModel;
using System.Management.Automation;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using (PowerShell ps = PowerShell.Create())
            {
                ps.AddScript(@"
Invoke-Command -ComputerName "Server1" {Get-PSDrive C} | Select-Object PSComputerName,Used,Free
");

                Collection<PSObject> result = ps.Invoke();
                foreach (var outputObject in result)
                {
                    // outputObject contains the result of the powershell script
                }
            }
        }
    }
}

Output:

outputObject.ToString()
"@{PSComputerName=Server1; Used=130904309760; Free=136322117632}"
6
  • Desired outcome is very unclear here. outputObject is already a real .NET object of type PSObject - what are you hoping to end up with? Commented Nov 14, 2023 at 17:24
  • you can ps.Invoke<MyCustomType>() too btw Commented Nov 14, 2023 at 17:40
  • @SantiagoSquarzon I suspect that's unlikely to help here, since the underlying object is a PSCustomObject :) Commented Nov 14, 2023 at 17:49
  • @MathiasR.Jessen Works fine with PSCustomObject here is an example of that: gist.github.com/santisq/… :) Commented Nov 14, 2023 at 17:53
  • I just learned this outputObject.Properties["PSComputerName"].Value "Server1" Commented Nov 14, 2023 at 17:58

1 Answer 1

2

Based on PSObject you can just use outputObject.Members / outputObject.Properties to get values and then uses their to fill your custom type.

Example: https://www.codeproject.com/Tips/5335001/Retrieving-data-from-executed-commands-in-PowerShe

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

2 Comments

Seems like I can get a couple of ways. Which one should I use? outputObject.Properties["PSComputerName"].Value "Server1" outputObject.Members["PSComputerName"].Value "Server1"
@Rod Depends on what you want access to. Members contains all adapted or intrinsic members (including any methods attached to the object or the underlying base type) - so if you just want field/property values: use Properties

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.