PowerShell environment

environment-variablespowershell

I am proficient in bash and having trouble understanding the environment in PowerShell. Is there any way equivalent to /usr/bin for adding executables to the environment? How is the environment represented in PowerShell–what is its type?

Best Answer

There is absolutely nothing special about /usr/bin on *nix file systems, except that it's a location which is in the PATH environment variable by default for all users. Windows has the same environment variable, but the only locations in it by default for all users are things like C:\Windows\System32.

You can use System32 as a bin folder, but you could also just create a new folder for bins. C:\bin would work, though by default it would be writable by all users so you might want to adjust the permissions, and then you could add it to the machine-wide PATH environment variable so all users can run things from it easily. Alternatively, consider a bin folder in each user's directory, with its path in the user's per-user PATH environment variable (when an environment variable is defined in both user and machine stores, it is concatenated in actual use, machine first).

PowerShell puts all environment variables in a virtual "drive" called Env: (similar to C: for files or HKLM: for the HKLM registry hive). Read more about it here: http://ss64.com/ps/syntax-env.html You can access the environment variables via $env:<VARNAME> like any other variable (the type is String); for example, you can append to PATH (note: Windows environment variable names are case-insensitive) as follows:

$env:path = $env:path + ";C:\foo\bar\baz"

This only sets for the current process (and its children), though. If you want to store the value in the registry so they are visible to other processes, or even other users (note: editing environment variables that affect other users requires Administrator privileges), the easiest way I know of is to use .NET classes (PowerShell is basically ".NETscript"). For example, to add this folder to the machine-wide PATH environment variable, you would do the following (as Admin):

[System.Environment]::SetEnvironmentVariable("path", $env:path + "C:\foo\bar\baz", "Machine")

The final parameter is the String representation of a value in the System.EnvironmentVariableTaget enum, as used by the System.Environment.SetEnvironmentVariable static method.

You can certainly create a script/cmdlet that would simplify calling this function. You can also use the [System.Environment]::GetEnvironmentVariable(name, [optional store]) static function to read environment variables directly from the User or Machine stores. Again, all environment variables are Strings (and when you get a collection of them, it's a Dictionary).