问题
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