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}"
outputObjectis already a real .NET object of typePSObject- what are you hoping to end up with?ps.Invoke<MyCustomType>()too btwPSCustomObject:)PSCustomObjecthere is an example of that: gist.github.com/santisq/… :)outputObject.Properties["PSComputerName"].Value "Server1"