Problem
You have a set of data (such as a hashtable or array) and want to save it to disk so that you can use it later. Conversely, you have saved structured data to a file and want to import it so that you can use it.
Solution
Use PowerShell’s ExportCliXml cmdlet to save structured data to disk, and the ImportCliXml cmdlet to import it again from disk.
For example, imagine storing a list of your favorite directories in a hashtable, so that you can easily navigate your system with a “Favorite CD” function. Example 85 shows this function.
Example 85. A function that requires persistent structured data
PS >$favorites = @{} PS >$favorites["temp"] = "c:\temp" PS >$favorites["music"] = "h:\lee\my music" PS >function fcd { >> param([string] $location) SetLocation $favorites[$location] >> } >> PS >GetLocation
Path
HKLM:\software
PS >fcd temp PS >GetLocation
Path
C:\temp
Unfortunately, the $favorites variable vanishes whenever you close PowerShell.
To get around this, you could recreate the $favorites variable in your profile, but another way is to export it directly to a file. This command assumes that you have already created a profile, and places the file in the same location as that profile:
PS >$filename = JoinPath (SplitPath $profile) favorites.clixml PS >$favorites | ExportCliXml $filename PS >$favorites = $null PS >$favorites PS >
Once it’s on disk, you can reload it using the ImportCliXml cmdlet, as shown in Example 86.
Example 86. Restoring structured data from disk
PS >$favorites = ImportCliXml $filename PS >$favorites
Name
Value
music
h:\lee\my music
temp
c:\temp
PS >fcd music PS >GetLocation
Path
H:\lee\My Music
Discussion
PowerShell provides the ExportCliXml and ImportCliXml cmdlets to let you easily move structured data into and out of files. These cmdlets accomplish this in a very datacentric and futureproof way—by storing only the names, values, and basic data types for the properties of that data.
By default, PowerShell stores one level of data: all directly accessible simple properties (such as the WorkingSet of a process) but a plaintext representation for anything deeper (such as a process’s
Threads collection). For information on how to control the depth of this export, type GetHelp ExportCliXml and see the explanation of the –Depth parameter.
After you import data saved by ExportCliXml, you again have access to the properties and values from the original data. PowerShell converts some objects back to their fully featured objects (such as System.DateTime objects), but for the most part does not retain functionality (for example, methods) from the original objects.