Home > Microsoft, PowerShell > PowerShell : Add Recursive Directories to PATH

PowerShell : Add Recursive Directories to PATH

October 19, 2009

As I continue to go script crazy (a bit) with PowerShell, I’ve noticed that my general scripts directory has grown quite a bit and is becoming a bit unmanagable.  Being a lover of neat and tidy, I wanted to separate ‘common’ scripts from ‘server-based’ and ‘task’ scripts.

Sounds easy enough, but that breaks part of my PowerShell profile—the part where I add the scripts directory to the path.  Moving those files out of that directory, even if they’re in subdirectories, would take them out of the path and I’d lose my [a..b]-{tab} goodness.

So, how to add the recursive structure to PATH?

It’s easy!

In my Profile, $scripts is a variable that contains a path to my ‘standard’ scripts directory based on whatever computer I’m currently logged into.

From there, simply use the built-in features of PowerShell.

gci $scripts |

                ? { $_.psIsContainer } |

                % { [System.Environment]::SetEnvironmentVariable(“PATH”,

                                $Env:Path + “;” + $_.FullName, “Process”) }

Verbatim: for each child object in $scripts that is a container, append the full name to PATH.

Exactly what I wanted and works like a champ.  Now I can move my scripts around, create new directories, the works—and each time I restart my console, it’ll detect the new directories and simply work—exactly like a shell should.

Categories: Microsoft, PowerShell
%d bloggers like this: