Close

PowerShell – Environment Variables

to set an environment variable, you can do this

[powershell]

[environment]::SetEnvironmentVariable("TestVar", "a simple string", "Machine")

[/powershell]

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:

[powershell]

$TestVar = [System.Environment]::GetEnvironmentVariable("TestVar","Machine")
"this variable contains: $TestVar"

[/powershell]

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

 

 

 

 

 

useful links:

http://technet.microsoft.com/en-us/library/ff730964.aspx (ready the part about "GetEnvironmentVariable")

 

http://www.thomas-franke.net/powershell-manage-passwords-credentials/