PoshCode Archive  Artifact Content

Artifact 19469679f8ee91000b3ef23e55b3fe34b630fad3ebcf11de2638669eb8b92bd0:

  • File env-PATH-permanently.ps1 — part of check-in [a5c69e2866] at 2018-06-10 13:27:16 on branch trunk — Add directory to Environment PATH variable permanently. Apply changes immediately without requiring reboot. (user: mnaoumov size: 1826)

# encoding: utf-8
# api: powershell
# title: $env:PATH permanently
# description: Add directory to Environment PATH variable permanently. Apply changes immediately without requiring reboot.
# version: 0.1
# author: mnaoumov
# license: CC0
# x-poshcode-id: 3537
# x-archived: 2014-05-13T20:57:24
# x-published: 2014-07-23T18:59:00
#
#
#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);
}