Add-EnvPath.ps1

Function Add-EnvPath{
  <#
      .SYNOPSIS
      Add Folder to Environment Variable PATH

      .DESCRIPTION
      Add Folder to Machine, User or Process to Environment Variable PATH

      .PARAMETER NewFolder
      Folder to add to PATH

      .PARAMETER VariableTarget
      Add NewFolder to Machine, User or Process Env Path Variable

      .INPUTS
      string - folder path

      .OUTPUTS
      List of the Path Variable after it has been changed

      .EXAMPLE
      Add-EnvPath -NewFolder 'C:\temp' -VariableTarget Machine
  #>

  [Cmdletbinding(SupportsShouldProcess)]
  param(
    [parameter(Mandatory,ValueFromPipeline,Position=0)]
    [ValidateScript({Test-Path -Path $_ -PathType Container})]
    [String[]]$NewFolder,
    [System.EnvironmentVariableTarget]$VariableTarget = [System.EnvironmentVariableTarget]::Machine
  )
  If ( ! (Test-LocalAdmin) ) { Write-Host 'Need to RUN AS ADMINISTRATOR first'; Return 1 }
  # Get the Current Search Path from the Environment keys in the Registry
  $OldPath = [environment]::GetEnvironmentVariable('PATH',$VariableTarget)

  # See if the new Folder is already IN the Path
  $PathasArray=($Env:PATH).split(';')
  If ($PathasArray -contains $NewFolder -or $PathAsArray -contains $NewFolder+'\') {
    Return "Folder already within `$ENV:PATH"
  }
  If (!($NewFolder[-1] -match '\')) { $Newpath = $Newpath+'\'}
  # Set the New Path
  $NewPath= $OldPath + ';' + $NewFolder
  if ( $PSCmdlet.ShouldProcess($NewFolder) ) {
    [environment]::SetEnvironmentVariable('PATH',$Newpath,$VariableTarget)
    $confirm = [environment]::GetEnvironmentVariable('PATH',$VariableTarget)
    # Show our results back to the world
    Return $confirm
  }
}