Dealing with CimObjects with PowerShell inside C#

為{幸葍}努か 提交于 2019-11-28 14:23:25

I don't think there is any easy way to convert PowerShell output to an easier to handle format. You need to 'manually' pull out the properties you want. For example, you can get the 'AllocatedSize' value like this:

var allocatedSize = results.First().Members["AllocatedSize"].Value;

If you want your own types based on these values, then you can do something like this:

Define your type (change the properties to suit the ones you want):

public class MyDisk
{
   public long AllocatedSize { get; set; }
   public string FriendlyName { get; set; }
   public bool IsBoot { get; set; }
   public int Number { get; set; }
}

Add a helper method that does the conversion:

private static MyDisk ConvertToMyDisk(PSMemberInfoCollection<PSMemberInfo> item)
{
    return new MyDisk
    {
        AllocatedSize = long.Parse(item["AllocatedSize")].Value.ToString()),
        FriendlyName = item["FriendlyName"].Value.ToString(),
        IsBoot = bool.Parse(item["IsBoot"].Value.ToString()),
        Number = int.Parse(item["Number"].Value.ToString())
    };
}

You can then convert the return values to your own type with some basic LINQ:

List<MyDisk> myDisks = results.Select(d => ConvertToMyDisk(d.Members)).ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!