-
-
Save mkropat/c1226e0cc2ca941b23a9 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 * |
When adding path to machine I get error: "Requested registry access is
not allowed"... is there some workaround?
@mrlee14 it always requires admin access. This script can't change that.
If you use
Add-EnvPathlike this:Add-EnvPath "C:\Foo"it will simply add that path to the current session, and that will work (for the current session). Note thatAdd-EnvPathcan take two parameters (参数) ,[string] $Pathand[string] $Container. If you don't set the second parameter (参数) ($Container) it will always default toSession. If you want to addC:\Footo either the User or System Environment var, do this:Add-EnvPath "C:\Foo" "User"or, alternative (替代) syntax (语法) :Add-EnvPath -Path "C:\Foo" -Container "Machine"
Add-EnvPath(and the other functions) only work if you import them first, of course, so do this before (or in your profile, for example):Import-Module -Name "C:\Your\Path\to\EnvPaths.psm1"
There was an error importing the module
Import-Module: C:\Users\brucm\Documents\PowerShell\Microsoft.PowerShell_profile.ps1:2
Line |
2 | Import-Module -Name "$HOME.config\powershell\EnvPaths.psm1"
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| File C:\Users\brucm\.config\powershell\EnvPaths.psm1 cannot be loaded. The file
| C:\Users\brucm\.config\powershell\EnvPaths.psm1 is not digitally signed. You cannot run this script on
| the current system. For more information about running scripts and setting execution policy, see
| about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.
this only can work after I execute this command with Administrator
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope CurrentUser
@brucmao yes, this is normal. On a fresh install, ExecutionPolicy is not set, which means that PowerShell is not allowed to run any scripts.
@mkropat Can you please tell me what is the benefit of this filtering | where { $_ } ?
Wouldn't the result be exactly the same without this?
@mkropat Can you please tell me what is the benefit of this filtering
| where { $_ }?
Wouldn't the result be exactly the same without this?
It filters out any records that is regarded as "falsy" values, including empty and null values.
Recommended change to Get-EnvPath:
function Get-EnvPath {
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Machine', 'User', 'Session')]
[string] $Container
)
$containerMapping = @{
Machine = [EnvironmentVariableTarget]::Machine
User = [EnvironmentVariableTarget]::User
}
$containerType = $containerMapping[$Container]
switch( $Container ){
"Session" {
$env:Path -split ";" |
where { $_ }
}
default {
[Environment]::GetEnvironmentVariable('Path', $containerType) -split ';' |
where { $_ }
}
}
}instead of hardcode ";"
Would you mind replacing it with [IO.Path]::PathSeparator?
I wrote safer approach
function Resolve-EnvPath {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[alias('path', 'literalPath')]
[string[]]$paths
)
begin {
$resolved = @()
}
process {
foreach ($path in $paths) {
$path = $path.Trim(@('"', "'", "`t", ' '))
# If it exists, resolve it fully.
if (Test-Path -Literal $path) {
$fullPath = (Resolve-Path -Literal $path).ProviderPath
$resolved += $fullPath.TrimEnd('\')
continue
}
# If it doesn't exist, still normalize it relative to current location.
$fullPath = [System.IO.Path]::GetFullPath($path)
if ($fullPath.Length -gt 3 -and $fullPath.EndsWith('\')) {
$fullPath = $fullPath.TrimEnd('\')
}
$resolved += $fullPath
}
return $resolved
}
}
function Get-EnvPathList {
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[ValidateSet('Session', 'User', 'Machine')]
[string]$scope = 'Session'
)
switch ($scope) {
'Session' {
$rawPath = $env:Path
}
'User' {
$rawPath = [Environment]::GetEnvironmentVariable('Path', [EnvironmentVariableTarget]::User)
}
'Machine' {
$rawPath = [Environment]::GetEnvironmentVariable('Path', [EnvironmentVariableTarget]::Machine)
}
}
if ([string]::IsNullOrWhiteSpace($rawPath)) {
return @()
}
return @(
$rawPath -split ';' |
ForEach { $_.Trim() } |
Where { -not [string]::IsNullOrWhiteSpace($_) } |
Select -Unique
)
}
<#
.EXAMPLE
Get-EnvPath notepad
envget notepad
# C:\Windows\system32\notepad
.EXAMPLE
envget conemu-maximus5 -Scope User
# C:\Users\ToYu\cmder\vendor\conemu-maximus5
.EXAMPLE
envget C:\Users\ToYu\cmder\vendor\conemu-maximus5
#>
function Get-EnvPath {
[CmdletBinding()]
[alias('envget', 'finddir', 'findfolder')]
param(
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[alias('name', 'path', 'literalPath')]
[string[]]$paths,
[Parameter(Position = 1)]
[ValidateSet('Session', 'User', 'Machine')]
[string]$scope = 'Session'
)
begin {
$envPaths = Get-EnvPathList $scope
$matches = @()
}
process {
foreach ($path in $paths) {
if ([string]::IsNullOrWhiteSpace($path)) {
continue
}
$isPathLike = [System.IO.Path]::IsPathRooted($path) -or
$path.Contains('\') -or
$path.Contains('/')
$resolved = $isPathLike ? (Resolve-EnvPath $path) : ''
$isFound = $false
foreach ($envPath in $envPaths) {
if ($isPathLike -and ($envPath -ieq $resolved)) {
$matches += $envPath
$isFound = $true
continue
}
$name = [System.IO.Path]::GetFileName($path)
$base = [System.IO.Path]::GetFileNameWithoutExtension($path)
$envName = [System.IO.Path]::GetFileName($envPath)
$envBase = [System.IO.Path]::GetFileNameWithoutExtension($envPath)
if (
$envName -ieq $name -or
$envBase -ieq $base -or
$envName -like "$name*" -or
$envBase -like "$base*"
) {
$matches += $envPath
$isFound = $true
}
}
if (-not $isFound) {
Write-Error "No matching entry found for `"$path`" in $scope PATH"
}
}
return $matches
}
}
function Update-Environment {
param(
[int]$TimeoutMs = 50
)
Add-Type @'
using System;
using System.Runtime.InteropServices;
public static class NativeMethods {
public const uint WM_SETTINGCHANGE = 0x001A;
public const uint SMTO_ABORTIFHUNG = 0x0002;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd,
uint Msg,
IntPtr wParam,
string lParam,
uint fuFlags,
uint uTimeout,
out IntPtr lpdwResult);
}
'@
$result = [IntPtr]::Zero
[void][NativeMethods]::SendMessageTimeout(
[IntPtr]0xFFFF,
[NativeMethods]::WM_SETTINGCHANGE,
[IntPtr]::Zero,
'Environment',
[NativeMethods]::SMTO_ABORTIFHUNG,
$TimeoutMs,
[ref]$result
)
}
function Set-EnvironmentVariable {
[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory)]
[string]$Name,
[Parameter(Position = 1, Mandatory, ValueFromPipeline)]
[object]$Value,
[Parameter(Position = 2)]
[ValidateSet('Session', 'User', 'Machine')]
[string]$Scope = 'User'
)
if ($Value -eq '') {
Remove-Item Env:$Name -ErrorAction SilentlyContinue
} else {
Set-Item Env:$Name -Value $Value
}
switch ($Scope) {
'User' {
$regPath = 'HKCU:\Environment'
if ($Value -eq '') {
Remove-ItemProperty -Path $regPath -Name $Name -ErrorAction SilentlyContinue
} else {
Set-ItemProperty -Path $regPath -Name $Name -Value $Value -Force
}
}
'Machine' {
$regPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
if ($Value -eq '') {
Remove-ItemProperty -Path $regPath -Name $Name -ErrorAction SilentlyContinue
} else {
Set-ItemProperty -Path $regPath -Name $Name -Value $Value -Force
}
}
}
Update-Environment
}
<#
.EXAMPLE
Add-EnvPath C:\Users\ToYu\ripgrep
.EXAMPLE
Add-EnvPath -Path .\Microsoft\WindowsApps -Scope Session
.EXAMPLE
Add-EnvPath -Path C:\Users\ToYu\Notepad++\notepad++.exe -Scope Machine
#>
function Add-EnvPath {
[CmdletBinding()]
[alias('envadd')]
param(
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[alias('path', 'literalPath')]
[string[]]$paths,
[Parameter(Position = 1)]
[ValidateSet('Session', 'User', 'Machine')]
[string]$scope = 'User'
)
begin {
# Always keep the current session in sync
$isSessionOnly = ($scope -eq 'Session')
$sessionPaths = Get-EnvPathList 'Session'
$envPaths = $isSessionOnly ? @() : (Get-EnvPathList $scope)
$sessionValues = @()
$envValues = @()
}
process {
foreach ($path in $paths) {
# Values are writed separately for the current session ($env:Path)
# and for the specified scope (environment)
$resolved = Resolve-EnvPath $path
if (-not [System.IO.Path]::IsPathRooted($resolved)) {
Write-Error "Path must be absolute: `"$path`" -> `"$resolved`""
continue
}
if ($path -notin $sessionPaths) {
$sessionValues += $path
} elseif ($isSessionOnly) {
# Current session supposed to be updated explicitly
Write-Error "Path already exists in current session: `"$path`" -> `"$resolved`""
}
if ($isSessionOnly) {
continue
}
# Persistent path
if ($path -notin $envPaths) {
$envValues += $path
} else {
Write-Error "Path already exists in $scope PATH: `"$path`" -> `"$resolved`""
}
}
}
end {
if ($sessionValues.count) {
$env:Path = `
@((Get-EnvPathList 'Session'), $sessionValues) |
Join-String -sep ';'
}
if ($isSessionOnly) {
return $sessionValues
}
if ($envValues.count) {
@((Get-EnvPathList $scope), $envValues) |
Join-String -sep ';' |
Set-EnvironmentVariable -name 'Path' -scope $scope
}
return $envValues
}
}
<#
.EXAMPLE
Remove-EnvPath C:\Users\ToYu\ripgrep
.EXAMPLE
Remove-EnvPath ripgrep
.EXAMPLE
Remove-EnvPath -Path .\Microsoft\WindowsApps -Scope Session
.EXAMPLE
Find-EnvPath git, gitbutler, but | Split-Path -Parent | Remove-EnvPath
#>
function Remove-EnvPath {
[CmdletBinding()]
[Alias('envrem')]
param(
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[alias('path', 'name')]
[string[]]$paths,
[Parameter(Position = 1)]
[ValidateSet('Session', 'User', 'Machine')]
[string]$scope = 'User'
)
begin {
# Values are writed separately for the current session ($env:Path)
# and for the specified scope (environment)
$isSessionOnly = ($scope -eq 'Session')
$sessionValues = @()
$envValues = @()
}
process {
$sessionValues = Get-EnvPath $paths 'Session' -ErrorAction ($isSessionOnly ? 'Continue' : 'SilentlyContinue')
if (-not $isSessionOnly) {
$envValues = Get-EnvPath $paths $scope -ErrorAction 'Continue'
}
}
end {
if ($sessionValues.count) {
$env:Path = Get-EnvPathList 'Session' |
Where { $_ -notin $sessionValues } |
Join-String -sep ';'
}
if ($isSessionOnly) {
return $sessionValues
}
if ($envValues.count) {
$value = Get-EnvPathList $scope |
Where { $_ -notin $envValues } |
Join-String -sep ';' |
Set-EnvironmentVariable -name 'Path' -scope $scope
}
return $envValues
}
}[Environment]::SetEnvironmentVariable implementation is slow because it broadcasts a system-wide environment change via WM_SETTINGCHANGEand waits for ALL PROCESSES to process it. This can block for roughly 20 seconds or more, which is why calls appear when updating PATH or other environment values. So I wrote my own Set-EnvironmentVariable.




@simohakki
If you use
Add-EnvPathlike this:Add-EnvPath "C:\Foo"it will simply add that path to the current session, and that will work (for the current session).Note that
Add-EnvPathcan take two parameters,[string] $Pathand[string] $Container. If you don't set the second parameter ($Container) it will always default toSession.If you want to add
C:\Footo either the User or System Environment var, do this:Add-EnvPath "C:\Foo" "User"or, alternative syntax:
Add-EnvPath -Path "C:\Foo" -Container "Machine"Add-EnvPath(and the other functions) only work if you import them first, of course, so do this before (or in your profile, for example):Import-Module -Name "C:\Your\Path\to\EnvPaths.psm1"