Add-EnvPath.ps1
Function Add-EnvPath{ [Cmdletbinding(SupportsShouldProcess)] param( [parameter(Mandatory,ValueFromPipeline,Position=0)] [ValidateScript({Test-Path -Path $_ -PathType Container})] [String[]]$AddedFolder, [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 $AddedFolder -or $PathAsArray -contains $AddedFolder+'\') { Return "Folder already within `$ENV:PATH" } If (!($AddedFolder[-1] -match '\')) { $Newpath = $Newpath+'\'} # Set the New Path $NewPath= $OldPath + ';' + $AddedFolder if ( $PSCmdlet.ShouldProcess($AddedFolder) ) { [environment]::SetEnvironmentVariable('PATH',$Newpath,$VariableTarget) $confirm = [environment]::GetEnvironmentVariable('PATH',$VariableTarget) # Show our results back to the world Return $confirm } } |