Caching Objects in PowerShell – Part 2

In my previous post about this subject, I demonstrated how to cache objects using an XML file. Let’s take a look at how to load, manipulate and save the data again.

Since the Export-Clixml cmdlet retains the data type in the XML file, we can perform actions on the objects in memory that are type-specific without having to cast the objects.  This means if we have an integer value, we can increment the count by calling the ++ operator.  Likewise, if we have a DateTime object, we can call type-specific methods such as .ToUniversalTime().  I think this is very cool and I wish I’d discovered this sooner. 

Loading the XML back into memory couldn’t be easier:

$DBCache = Import-Clixml C:\DatabaseCache.xml

Using the data created in part 1, let’s assume we just created a new mailbox on Database-1.  With the below code, we can easily take the objects in memory and increment the count to show the new updated mailbox number.  Another example would be adding time to the Timestamp attribute before we save .

($DBCache | where {$_.DatabaseName –eq “Database-1”}).UserCount++

foreach ($DBItem in $DBCache) { $DBItem.Timestamp.AddHours(3) }

Once the objects are modified, simply overwrite the XML file with the updated data:

$DBCache | Export-Clixml “C:\DatabaseCache.xml”

I realize this is a very simple example but the principal applies to any class and any of those class methods.

Comments (0)

Skip to main content