Question

I use a Collections.Generic.List[object] instead of a PowerShell array in my script, in order to have ".add()" and also because of speed (the list is quite large).

When I export the list via Export-Clixml and reimport it again, it's not a generic-list any more; it's a standard array, and ".add()" does not work any more.

Oddly (or not), when I place another generic list object inside the first one, it survives the export-import process. Why and how do I work around that?

$list = New-Object System.Collections.Generic.List[object]
$entry = New-Object Psobject -Property @{
    Test = "1"
    Sublist = (New-Object System.Collections.Generic.List[object])
}
$list.add($entry)

$list | Export-Clixml D:\text.xml
$newlist = import-clixml D:\text.xml


# Produces this export:

*<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Management.Automation.PSCustomObject</T>
      <T>System.Object</T>
    </TN>
    <MS>
      <S N="Test">1</S>
      <Obj N="Sublist" RefId="1">
        <TN RefId="1">
          <T>System.Collections.Generic.List`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
          <T>System.Object</T>
        </TN>
        <LST />
      </Obj>
    </MS>
  </Obj>
</Objs*>
Was it helpful?

Solution

The pipeline is doing that to you. The pipeline will "unroll" arrays and collections, but multiple returns are always re-assembled into arrays. The arraylist inside an arraylist works because it only unrolls one level deep, so the first (outer) arraylist got "unrolled" and the second (inner) arraylist got passed through intact.

Try it this way:

Export-Clixml -InputObject $list -Path d:\text.xml
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top