Sunday, August 19, 2007

Creating Environment variables


To list all environment variables you dir the env: PSdrive


dir env:

-or-

>> [Environment]::GetEnvironmentVariables();



# truncated list

Name                 Value
----                     -----
Path                       C:\Program Files\Windows Resource Kits\Tools\;C:\Program F
SESSIONNAME         Console
PATHEXT                .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PSC1;.VB
....
....
....
ALLUSERSPROFILE   C:\Documents and Settings\All Users
OS                          Windows_NT
HOMEDRIVE             C:




Creating Variables

Variables can be created for the current process, user or machine context.
Process variables typically will be lost once the process exists (volatile), while user or machine are permanent and stored in the registry.

You can use the .NET SetEnvironmentVariable Method to create , modify or delete an environment variable. The method syntax is as follows:


[Environment]::SetEnvironmentVariable(<name>,<value>,<EnvironmentVariableTarget>);



EnvironmentVariableTarget can hold one of the following constants:
Process = 0
User = 1
Machine = 2

All Italic lines were copied from the SetEnvironmentVariable method web page.



Process variable


"If the target parameter is not Process, the environment variable is not automatically copied to the current process."

Correct me if I'm wrong but I think the "is not" should be "is". Listing the current process environment items shows the new created "Shay" item. Anyway, here is the create process:


>> [Environment]::SetEnvironmentVariable("Shay","Levi","Process");


User variable


"If target is User, the environment variable is stored in the Windows operating system registry key reserved for the current user, and is copied to the current process when the user who stored the variable starts a new process."

>> [Environment]::SetEnvironmentVariable("Shay","Levi","User");


Screen shot taken from the System properties applet



Machine variable


"If target is Machine, the environment variable is stored in the Windows operating system registry key reserved for the local machine, and is copied to the current process when any user on the local machine starts a new process."


>> [Environment]::SetEnvironmentVariable("Shay","Levi","Machine");




Delete variables


To delete a variable assign the $null to the item value

[Environment]::SetEnvironmentVariable("Shay",$null,0); # Process
[Environment]::SetEnvironmentVariable("Shay",$null,1); # User
[Environment]::SetEnvironmentVariable("Shay",$null,2); # Machine





No comments: