Dealing with CimObjects with PowerShell inside C#

北战南征 提交于 2019-11-27 08:47:25

问题


I have a snippet that executes a PowerShell script

using (var ps = PowerShell.Create())
{
    ps.AddScript("function Test() { return Get-Disk -Number 0 } ");
    ps.Invoke();
    ps.AddCommand("Test");
    var results = ps.Invoke();
    var disk = results.First();

    MyDisk myDisk = // do something to convert disk to myDisk
}

Debuggin, it get his inside disk:

How I'm supposed to deal with this object (CimObject)? I would like to get the values from the "Name" and "Number" properties.

Just to clarify, the object I'm trying to deal is the same type as this (run into PowerShell as admin)

PS C:\windows\system32> $disk = Get-Disk -Number 0
PS C:\windows\system32> $disk.GetType();

How do I interact with this?

Thank you!


回答1:


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();


来源:https://stackoverflow.com/questions/51099688/dealing-with-cimobjects-with-powershell-inside-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!