Tuesday, July 29, 2008

The PATH in Powershell

One of the things I wanted to do when I had a Blog was to post a recap of the interesting things I learn periodically, specially if it took me a while to learn them or if there was some complications for me to understand them.
I will start this today with this posting.


The PATH in Powershell

Maybe because I never formally read much about powershell, maybe because I did not bother enough to find it sooner, or for whatever reason, I had never found out what to do in order to be able to execute my scripts as just another PS command, meaning be able to use
my-script
instead of
. my-script.ps1

Yesterday I decided to research on it and after some goggling I got a clue: The Script's directory MUST be in the PATH, meaning that even if you are standing right in the Script's directory, you won't be able to execute it as a command unless the directory is in the PATH. Crazy, isn't it ???

Okay,now that I knew that I need to figure out 2 things:
  1. How to read the path from Powershell (I found that Path and $path did not work), and
  2. How to change it (To be able to add my own directories)

A little more googling revealed that to get the PATH I only need to query the Environmental variables:
$env:path

Easy, right ???? ... Then, Why didn't I figure it our sooner ???

To add items to the pat, it's just as simple:

$env:path = $env:path + ";E:\My Scripts\Powershell\"

Now, that script that i was only able to execute as:
& "E:\My Scripts\Powershell\my-script.ps1"
can now be executed as:
my-script


To see if an specific directory is part of the PATH, we can use simple string functions:

($env:path -match 'My Scripts\\Powershell')

(Notice the double slash in order for the slash not to be considered as a REGEX command)

Well, not "rocket science", but it did took me a while to put all the pieces together, and I hope that I'll save some time to the next person trying to accomplish this.

No comments: