简体   繁体   中英

PSObject cast to List<String>

Handle the PSObject in C# For command :

Get-SCVirtualNetworkAdapter -All

One of the Response Object :

IPv4Addresses : {12.12.12.12}

Serialized data :

<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>Deserialized.System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
      <T>Deserialized.System.Object</T>
    </TN>
    <LST>
      <S>192.168.11.22</S>
    </LST>
  </Obj>
</Objs>

I want to get the

<LST>
          <S>192.168.11.22</S>
</LST>

as

List<String>

You can use any xml parser for this. I will prefer linq to xml.

var xml=XElement.Load(xmlFilePath);
var nsManager=new XmlNamespaceManager(new XmlNameTable());
nsManager.AddNamespace("ns1",@"http://schemas.microsoft.com/powershell/2004/04");
var list=xml.XPathSelectElements("//ns1:LST/ns1:S",nsManager)
             .Select(element=>element.Value);

PS: You need to add System.Xml , System.Xml.Linq and System.Xml.XPath namespaces in the using statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM