Friday, September 27, 2013

Setting Environment Variable with Powershell

In this article I will give you a quick little script that will help you set environment variables that you can then call from any other script.
There are two ways to set Environment Variables and a couple ways to call them, we will start with the standard way of doing it.
setx
Lets say that you want to set your Home Environment, for instance you have a Development or QA server farm.

setx /m Home_Env "My_Company_QA"; This particular Command would set a system variable named Home_Env and the value to "My_Company_QA". This value can be seen in
"My Computer-Properties-Advanced System Settings-Environment Variables it is also written to the registry"

The second way, and less used is to write the value directly to the registry, which essentially achieves the same goal. $EnvRegKey01 = "HKLM:\System\ControlSet001\Control\Session Manager\Environment"
cd $EnvRegKey01
New-ItemProperty -Path $EnvRegKey01\ -Name "Home_Env" -Value "My_Company_QA"
This would accomplish the same as the above; however it directly sets it to the registry. Now if the ItemProperty already exists you can use a number of different options to the -ItemProperty such as:
remove-, clear-, and rename-. Just so as to not deal with writing in checks to my script I typically just run the remove first then the new. If your key does not exist it will throw an error though.

Now to Call the value in your other scripts you need to know that the standard call is Get-ChildItem or GCI, but this will not work if it is run in the same session that you set the value, so you will have to close and reopen powershell. However there is a way around that. But first the standard way to grab your value.
Get-ChildItem env:Home_Env
#to actually use it as a variable you will need to store it, I will use the shortened version
$HomeEnv = (GCI env:Home_Env).value
#Now $HomeEnv is -eq to "My_Company_Qa"

Now lets say you need the value in the same session you are in, to do this you will need to directly call the Registry value and write it to your variable
$HomeEnv = (Get-ItemProperty -Path $EnvRegKey01\ -Name "Home_Env").home_env