【发布时间】:2016-10-25 02:22:21
【问题描述】:
我正在尝试在 PowerShell 中学习 XML 序列化。所以,我正在制作一个简单的联系人列表来序列化和反序列化。我遇到的问题是Contact 对象在我使用Import-CliXml 导入时表现不同。
这是我现在正在尝试的:
class Contact {
[string]$FirstName;
[string]$LastName;
[Int64]$PhoneNumber; }
$bob = new-object Contact
$bob.FirstName = "Bob"
$bob.LastName = "Johnson"
$bob.PhoneNumber = 1235589876
$bill = new-object Contact
$bill.FirstName = "Bill"
$bill.LastName = "Carson"
$bill.PhoneNumber = 1235589875
$ContactList = new-object System.Collections.Generic.List[Contact]
$ContactList.Add($bob)
$ContactList.Add($bill)
[xml]$data = $ContactList | convertto-xml
new-item "C:\Users\Public\Documents\Contacts.xml"
$data | export-clixml "C:\Users\Public\Documents\Contacts.xml"
[xml]$ImportedData = import-clixml "C:\Users\Public\Documents\Contacts.xml"
$ImportedList = new-object System.Collections.Generic.List[Contact]
$ImportedList = $ImportedData.Objects.Object
导入的List[Contact] 具有Contact 对象的集合,但我似乎无法从它们的属性中获取信息。例如,当我尝试以下操作时出现空行:
$ImportedList | foreach-object { write-host $_.FirstName }
我知道这些对象在那里,因为我从$ImportedList 得到了回报:
$ImportedList
Type Property
---- --------
Contact {FirstName, LastName, PhoneNumber}
Contact {FirstName, LastName, PhoneNumber}
我正试图让它返回与 $ContactList 相同的内容:
$ContactList
FirstName LastName PhoneNumber
--------- -------- -----------
Bob Johnson 1235589876
Bill Carson 1235589875
任何帮助将不胜感激。
【问题讨论】:
-
跳过
ConvertTo-Xml步骤,改为使用$ContactList |Export-CliXml
标签: xml powershell deserialization generic-list