Public/Add-EnvPath.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Function Add-EnvPath {
  <#
      .SYNOPSIS
      Add a Folder to Environment Variable PATH
 
      .DESCRIPTION
      Add Folders to Environment Variable PATH for Machine, User or Process scope
      And removes missing PATH locations
 
      .PARAMETER Path
      Folder or Folders to add to PATH
 
      .PARAMETER VariableTarget
      Which Env Path the directory gets added to.
      Machine, User or Process
       
      .PARAMETER Clean
      Remove all Folder Paths that no longer exist.
 
      .INPUTS
      [String] - Folder Path, accepts multiple folders
 
      .OUTPUTS
      String - List of the New Path Variable
 
      .EXAMPLE
      Add-EnvPath -Path 'C:\temp' -VariableTarget Machine
  #>

  param(
    [Parameter(Mandatory,ValueFromPipeline)]
    [ValidateScript({
          if (-not (Test-Path -Path $_ -PathType Container)) {
            throw 'Path must be a Folder'
          }
          if (-not ([System.IO.Path]::IsPathRooted($_))) {
            throw 'Path must be absolute, such as - C:\Program Files\Notepad++'
          }
          return $true
    })]
    [String[]]$Path,
    [System.EnvironmentVariableTarget]$VariableTarget = [System.EnvironmentVariableTarget]::Machine,
    [switch]$Clean
  )
  begin {
    if (-not (Test-IfAdmin)) { throw 'RUN AS ADMINISTRATOR' }
    $OldPath = [System.Environment]::GetEnvironmentVariable('PATH',$VariableTarget).Split(';').TrimEnd('\')
    if ($Clean) {
      $OldPath = $OldPath | Convert-Path -ErrorAction SilentlyContinue
    }
    $NewPath = [System.Collections.ArrayList]::new()
    $NewPath.AddRange($OldPath)
  }
  process{
    foreach($NDir in $Path) {
      $NDir = (Convert-Path -Path $NDir -ErrorAction SilentlyContinue).TrimEnd('\')
      if ($NewPath -notcontains $NDir) { $null = $NewPath.Add($NDir) }
      else { Write-Warning -Message ('SKIPPING: {0} ' -f $NDir) }
    }
  }
  end {
    [System.Environment]::SetEnvironmentVariable('PATH',(($NewPath | Sort-Object -Unique) -join ';'),$VariableTarget)
    $Confirm = [System.Environment]::GetEnvironmentVariable('PATH',$VariableTarget).Split(';')
    return $Confirm
  }
}