SilverViper
SilverViper

Reputation: 679

How to store variables to disk so you can use them next time the PowerShell script runs?

I would like to store a variable to disk or registry so I can use it the next time I run the scheduled script? Preferably an one-liner or two...

Cheers, Roy

Upvotes: 15

Views: 15932

Answers (1)

Keith Hill
Keith Hill

Reputation: 201592

$foo | Export-CliXml foo.xml

then later

$foo = Import-CliXml foo.xml

Note that if $foo represents a live object, when you restore it, you are only going to get its properties. However the type information is more-or-less preserved. For example if you save out a System.Diagnostics.Process object, when you rehydrate it you will have a Deserialzed.System.Diagnostics.Process object.

BTW if you need to store/retrieve multiple variables, you can do that like so:

Get-Variable bla* | Export-Clixml vars.xml
Import-Clixml .\vars.xml | %{ Set-Variable $_.Name $_.Value }

Upvotes: 34

Related Questions