Iris Classon
Iris Classon - In Love with Code

Setting and searching Environment Variables in PowerShell

As you know I’m a PowerShell fan and the other I was trying to convince one of my coworkers to give it a try. We were trying to do some remote debugging with Weinre via node and not so surprisingly we had to set some environment variables to be able to run all the commands from the console.

You might be familiar with this, if you try to execute/run an alias that doesn’t exist you get told that it wasn’t in the path.

git : The term ‘git’ is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:3 char:2
+ git init
+ ~~~
+ CategoryInfo : ObjectNotFound: (git:String) [], CommandNotFoundExcept
ion
+ FullyQualifiedErrorId : CommandNotFoundException

This post is about how to deal with that, an a few more related things.

For those with little patience (like me) here is a little cheat list of some things you might want to do when working with environment variables.

Download the script here Change file extension to .ps1

To set a variable on user level on the machine, and not just for the current process you can use:
# Set variable on user level
[Environment]::SetEnvironmentVariable(“sublime3”, $path, “User”)

This is btw how you can locate something

If you need to set it for just that session you can use
# Set variable for process
$env:sublime3 = $path

If you want to add directly to the path you can do this, notice the extra semicolon and how we first add the current path before adding our. We don’t want to clear the path and just add one item.
# Add something to the path
$env:path = $env:path + “;$path”

If we want to search
# Search
Get-ChildItem ENV:sub* | Sort-Object Name

Here is the short version for that
# Short version for above
gc ENV:sub* | sort Name

To set an alias for a command we can do this
# Set alias for command for current session
Set-Alias sublime $path

To execute the command simply call it
# Execute command via alias
Sublime

To execute the variable we set earlier we need however need to tell PowerShell to treat it as an executable and that is done by using the ‘&’
# Execute path variable
& $env:sublime3

Comments

Leave a comment below, or by email.


Last modified on 2014-08-31

comments powered by Disqus