C#解析从PowerShell命令返回的项集合

C#解析从PowerShell命令返回的项集合,c#,list,parsing,powershell,C#,List,Parsing,Powershell,我正在尝试在C#中使用一些PowerShell Azure命令。当返回对象的属性是单个元素(string/int/)时,它的效果非常好,例如: foreach (PSObject xx in results) { PSMemberInfo ObjectId = xx.Properties["ObjectId"]; PSMemberInfo DisplayName = xx.Properties["DisplayName"]; } 因此,我

我正在尝试在C#中使用一些PowerShell Azure命令。当返回对象的属性是单个元素(string/int/)时,它的效果非常好,例如:

    foreach (PSObject xx in results)
    {
        PSMemberInfo ObjectId = xx.Properties["ObjectId"];
        PSMemberInfo DisplayName = xx.Properties["DisplayName"];
    }
因此,我可以通过ObjectId.Value或DisplayName.Value访问它们的值。它工作得很好

但是,如果返回的PowerShell属性的数据不是单个元素,而是某个元素的集合,则无法获取值。例如,如果我得到PS对象,如:

ExtensionData         : System.Runtime.Serialization.ExtensionDataObject
AccountEnabled        : True
Addresses             : {}
AppPrincipalId        : 00000000-0000-0000-0000-000000000000
DisplayName           : access_00000000-0000-0000-0000-000000000000
ObjectId              : 00000000-0000-0000-0000-000000000000
ServicePrincipalNames : {00000000-0000-0000-0000-000000000000, access_00000000-0000-0000-0000-000000000000}
TrustedForDelegation  : False
请注意,ServicePrincipalName和Address是列表。在本例中,
xx.Properties[“ServicePrincipalNames”]
包含一个列表,如果我简单地将其写入(
Console.WriteLine(xx.Properties[“ServicePrincipalNames”].Value);
),我将看到:“
System.Collections.Generic.List1[System.String]
”,因此这看起来像一个集合,尽管我无法对其进行迭代。如果我尝试:

foreach(var g in ...)
编译器带来一个错误,
xx.Properties[“ServicePrincipalNames”]。Value
是一个对象,没有任何枚举数

谷歌帮不了多少忙。有没有人有过这样的经历


谢谢

您可以将其显式强制转换为枚举器:

var principalNames = (List<string>)xx.Properties["ServicePrincipalNames"].Value;
foreach(var principalName in principalNames) {...}
var principalNames=(List)xx.Properties[“ServicePrincipalNames”].Value;
foreach(principalName中的var principalName){…}