PowerShell and PATH

If you’ve been using PowerShell for any length of time, you have definitely set up your profile. Mine is fairly straight forward. It’s stored in $profile, which in my case is H:\Documents\WindowsPowerShell\Microsoft.PowerShell_Profile.ps1 – an obnoxiously long name. I’d rather it be profile.ps1, but I digress.

Import-Module PathUtils
Import-Module posh-git

Add-Path -Directory "${env:ProgramFiles(x86)}\Git\bin"
Add-Path -Directory "${env:USERPROFILE}\AppData\Roaming\npm"

function global:prompt {
    $Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor
    Write-Host($pwd.ProviderPath) -nonewline
    return "> "

Start-SshAgent -Quiet

The posh-git module is for colorizing my prompt, and everything after the Add-Path cmdlets is associated with that – actually, it’s boilerplate from their example. The Add-Path is the bit of code that I wrote. It’s in a module called PathUtils and contains just one function:

function Add-Path {
      Adds a Directory to the Current Path
      Add a directory to the current path.  This is useful for
      temporary changes to the path or, when run from your
      profile, for adjusting the path within your powershell
      Add-Path -Directory "C:\Program Files\Notepad++"
    .PARAMETER Directory
      The name of the directory to add to the current path.

  param (
      HelpMessage='What directory would you like to add?')]

    $Path = $env:PATH.Split(';')

    foreach ($dir in $Directory) {
      if ($Path -contains $dir) {
        Write-Verbose "$dir is already present in PATH"
      } else {
        if (-not (Test-Path $dir)) {
          Write-Verbose "$dir does not exist in the filesystem"
        } else {
          $Path += $dir

    $env:PATH = [String]::Join(';', $Path)

Export-ModuleMember -Function Add-Path

This is fairly straight forward, but I’ve made it as all-encompassing as I could. You just use Add-Path <directory> and it will add that to the path. However, it’s not a permanent change, and that recently caused me a problem.

When Visual Studio (or any other program, for that matter) kicks off a command like bower or npm (or more appropriately, jspm, in my case), it does so in a cmd prompt – not a PowerShell prompt. The Add-Path cmdlet sets up a PowerShell only prompt. So I need to store my PowerShell prompt as the user path, permanently.

To do this, I use the following bit of code:

[Environment]::SetEnvironmentVariable("Path", $env:Path,[System.EnvironmentVariableTarget]::User)

This uses the .NET Framework to store the current path in the users environment. You can replace the ::User with ::Machine to store the path variable in the system environment, which is useful when you have just installed a new program.

Maybe I should write a Save-Path cmdlet as well?