Skip to content

Instantly share code, notes, and snippets.

@marcandjulien
Forked from mkropat/EnvPaths.psm1
Created August 28, 2022 03:20
Show Gist options
  • Save marcandjulien/fb943bc7d567d86c7a7a37ccb37b150e to your computer and use it in GitHub Desktop.
Save marcandjulien/fb943bc7d567d86c7a7a37ccb37b150e to your computer and use it in GitHub Desktop.
function Add-EnvPath {
param(
[Parameter(Mandatory=$true)]
[string] $Path,
[ValidateSet('Machine', 'User', 'Session')]
[string] $Container = 'Session'
)
if ($Container -ne 'Session') {
$containerMapping = @{
Machine = [EnvironmentVariableTarget]::Machine
User = [EnvironmentVariableTarget]::User
}
$containerType = $containerMapping[$Container]
$persistedPaths = [Environment]::GetEnvironmentVariable('Path', $containerType) -split ';'
if ($persistedPaths -notcontains $Path) {
$persistedPaths = $persistedPaths + $Path | where { $_ }
[Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
}
}
$envPaths = $env:Path -split ';'
if ($envPaths -notcontains $Path) {
$envPaths = $envPaths + $Path | where { $_ }
$env:Path = $envPaths -join ';'
}
}
function Remove-EnvPath {
param(
[Parameter(Mandatory=$true)]
[string] $Path,
[ValidateSet('Machine', 'User', 'Session')]
[string] $Container = 'Session'
)
if ($Container -ne 'Session') {
$containerMapping = @{
Machine = [EnvironmentVariableTarget]::Machine
User = [EnvironmentVariableTarget]::User
}
$containerType = $containerMapping[$Container]
$persistedPaths = [Environment]::GetEnvironmentVariable('Path', $containerType) -split ';'
if ($persistedPaths -contains $Path) {
$persistedPaths = $persistedPaths | where { $_ -and $_ -ne $Path }
[Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
}
}
$envPaths = $env:Path -split ';'
if ($envPaths -contains $Path) {
$envPaths = $envPaths | where { $_ -and $_ -ne $Path }
$env:Path = $envPaths -join ';'
}
}
function Get-EnvPath {
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Machine', 'User')]
[string] $Container
)
$containerMapping = @{
Machine = [EnvironmentVariableTarget]::Machine
User = [EnvironmentVariableTarget]::User
}
$containerType = $containerMapping[$Container]
[Environment]::GetEnvironmentVariable('Path', $containerType) -split ';' |
where { $_ }
}
Export-ModuleMember -Function *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment