在C#中使用PowerShell处理CimObjects

在C#中使用PowerShell处理CimObjects

本文介绍了在C#中使用PowerShell处理CimObjects的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行PowerShell脚本的代码段

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,它将其放入磁盘

Debuggin, it get his inside disk:

我应该如何处理该对象( CimObject )?我想从名称和数字属性中获取值。

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

为了澄清,我尝试处理的对象与此(以管理员身份运行到PowerShell中)

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

我该如何与之互动?

谢谢!

推荐答案

我认为没有简单的方法可以将PowerShell输出转换为易于处理的格式。您需要手动提取所需的属性。例如,您可以像这样获得'AllocatedSize'值:

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

然后,您可以使用一些基本的LINQ将返回值转换为您自己的类型:

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

这篇关于在C#中使用PowerShell处理CimObjects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:07