header image

Persisting PowerShell Objects

Posted by: | November 26, 2014 Comments Off on Persisting PowerShell Objects |

I was asked recently about persisting PowerShell objects. The idea was to test a particular property on a semi-regular basis and save the object with the highest value for the property.  If the next test has a higher value it is saved and overwrites the existing object.


There are a number of ways to do this – if you are running the test very frequently then you could keep the object in memory as a variable. If you are testing fairly infrequently then you may want to persist the object to disk.  The CliXml cmdlets are good for this.


Start by creating a reference object:

Get-Process -Name powershell | Export-Clixml -Path proc1.xml


Then run some more tasks in PowerShell to increase the CPU usage. You can do this with any property that will change over time.  CPU is an easy example. You can then run your test. I used an instance of ISE to do the test so I didn’t alter the value by running the test.


$proc = Get-Process -Name powershell

Get-ChildItem -Path .\proc1.xml

$psp = Import-Clixml -Path .\proc1.xml

if ($proc.CPU -gt $psp.CPU){

$proc | Export-Clixml -Path proc1.xml


Get-ChildItem -Path .\proc1.xml


Get the current data and test the saved file. Import the saved file.  Test the CPU values and if the new value is higher save the object by overwriting the file.  Repeat as required.


The help files for Export-CliXml and Import-CliXml should be read.

under: PowerShell

Comments are closed.