to set an environment variable, you can do this
AnnouncementYou can find all my latest posts on medium.
[environment]::SetEnvironmentVariable("TestVar", "a simple string", "Machine")
Note, I think you can set the value at sessions/user/machine level. In the above case I have set them to the machine level.
Now to retrieve an environmenment from somewhare else, e.g. from another script, do this:
$TestVar = [System.Environment]::GetEnvironmentVariable("TestVar","Machine")
"this variable contains: $TestVar"
You can only store strings as environment variables. That means that you can’t store object-variables as environment variables.
However you can output an object-variable to an xml file, and then import it back to an object variable again using import-Clixml and export-Clixml. With this approach all you need to is keep track of where you stored the outputted xml file, so that you can import as and when need.
A common use for this is to store your “pscredential” object
http://technet.microsoft.com/en-us/library/ff730964.aspx (ready the part about “GetEnvironmentVariable”)