C#parse从PowerShell命令返回的项目集合

时间:2015-08-05 08:44:58

标签: c# list parsing powershell

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

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

因此,我可以通过ObjectId.Value或DisplayName.Value访问它们的值。它很棒。

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

xx.Properties["ServicePrincipalNames"]

请注意,ServicePrincipalNames和Addresses是列表。在这种情况下,Console.WriteLine(xx.Properties["ServicePrincipalNames"].Value);包含一个列表,如果我只是WriteLine它(System.Collections.Generic.List1[System.String]),我会看到:" foreach(var g in ...) "所以这看起来像一个集合,虽然我不能迭代它。如果我尝试:

xx.Properties["ServicePrincipalNames"].Value

编译器带来错误,setBoundsToWorld是一个对象,没有任何枚举器。

谷歌并没有多大帮助。以前有经验的人吗?

由于

1 个答案:

答案 0 :(得分:2)

您可以明确地将其转换为枚举器:

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