[PowerShell] Add directory to Environment PATH variable

Interesting part here is ApplyImmediately parameter, which allows newly created processes to use updated PATH without rebooting.
NOTE: existing processes (such as PowerShell) cannot use updated PATH. You should rerun the process.

#requires -version 2

param(
    [string] $AddedFolder,
    [bool] $ApplyImmediately = $true
)

$environmentRegistryKey = 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment'

$oldPath = (Get-ItemProperty -Path $environmentRegistryKey -Name PATH).Path

# See if a new folder has been supplied.

if (!$AddedFolder)
{
    Write-Warning 'No Folder Supplied. $ENV:PATH Unchanged'
    return
}

if ($ENV:PATH | Select-String -SimpleMatch $AddedFolder)
{
    Write-Warning 'Folder already within $ENV:PATH'
    return
}

$newPath = $oldPath + ’;’ + $AddedFolder

Set-ItemProperty -Path $environmentRegistryKey -Name PATH -Value $newPath

if ($ApplyImmediately)
{
    if (-not ("Win32.NativeMethods" -as [Type]))
    {
        # import sendmessagetimeout from win32
        Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @"
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessageTimeout(
        IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,
        uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
"@
    }

    $HWND_BROADCAST = [IntPtr] 0xffff;
    $WM_SETTINGCHANGE = 0x1a;
    $result = [UIntPtr]::Zero

    # notify all windows of environment block change
    [Win32.Nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, "Environment", 2, 5000, [ref] $result);
}
Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

2 Responses to [PowerShell] Add directory to Environment PATH variable

  1. Sick try mate. Love the post.

  2. Music addiction serves as a surrogate for lack of human bonds. Music can pierce the heart directly; it takes no mediation. Weekly Drum & Bass mixtapes posted each and every Wednesday. Hear us on MySpace.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s