Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 318
SilverViper Avatar asked Oct 22 '09 09:10

SilverViper


People also ask

How do you store variables in PowerShell?

By default, the variables that you create at the PowerShell command line exist only while the PowerShell window is open. When the PowerShell windows is closed, the variables are deleted. To save a variable, add it to your PowerShell profile. You can also create variables in scripts with global, script, or local scope.

How do you pass a variable in a PowerShell script?

How do I pass parameters to PowerShell scripts? Passing arguments in PowerShell is the same as in any other shell: you just type the command name, and then each argument, separated by spaces. If you need to specify the parameter name, you prefix it with a dash like -Name and then after a space (or a colon), the value.

Where are PowerShell variables stored?

In PowerShell, environment variables are stored in the Env: "drive", accessible through the PowerShell environment provider, a subsystem of PowerShell. This isn't a physical drive, but a virtual file system. Environment variables convey information about your login session to your computer.


1 Answers

$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 }
like image 172
Keith Hill Avatar answered Oct 03 '22 14:10

Keith Hill