Adding directory to Systemvariables Path in CMD - windows

Iam trying to add a directory permanently to Path via CMD. When i try to use the command:
setx path "%path%;C:\Program Files (x86)\chromedriver\chromedriver.exe"
it only saves it to the uservariables Path. Is there a way to add it to the systemvariables Path by using CMD?

This is PowerShell code. There is probably some way to do it with a cmd-only reg.exe, but I have not been down that path. If you are on a supported Windows system, PowerShell will be available.
To do this, you will want to retrieve the current variable values before interpolation (resolving). To do that for the user PATH variable:
(Get-Item -Path 'HKCU:\Environment').GetValue(
'PATH', # the registry-value name
$null, # the default value to return if no such value exists.
'DoNotExpandEnvironmentNames' # the option that suppresses expansion
)
To get the system PATH variable:
(Get-Item -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment').GetValue(
'PATH', # the registry-value name
$null, # the default value to return if no such value exists.
'DoNotExpandEnvironmentNames' # the option that suppresses expansion
)
Once you have the current, pre-interpolation PATH variable value, it can be changed before using Set-Item or setx.exe. Setting the system path will probably require Administrator permission, or should.

Related

How to set Rust's cargo directory in windows PATH?

I want unnatended install of rust, so I did this little script:
Write-Host "Installing Rust..." -ForegroundColor Cyan
$exePath = "$env:TEMP\rustup-init.exe"
Write-Host "Downloading..."
(New-Object Net.WebClient).DownloadFile('https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe', $exePath)
Write-Host "Installing..."
cmd /c start /wait $exePath -y
Remove-Item $exePath
$addPath = "$env:USERPROFILE\.cargo\bin"
[Environment]::SetEnvironmentVariable('PATH', $env:PATH, $addPath)
but I get
virtualbox-iso: Cannot convert argument "target", with value: "C:\Users\vagrant\.cargo\bin", for "SetEnvironmentVariable" to type
virtualbox-iso: "System.EnvironmentVariableTarget": "Cannot convert value "C:\Users\vagrant\.cargo\bin" to type
virtualbox-iso: "System.EnvironmentVariableTarget". Error: "Unable to match the identifier name C:\Users\vagrant\.cargo\bin to a valid
it looks like a text cannot be converted to a PATH type? What does it mean?
The immediate solution to your problem is that you need to call [Environment]::SetEnvironmentVariable() as follows:
# Modify the user-level PATH definition.
# To modify the machine-level definition, use 'Machine' instead of user 'User',
# but you then need to run with ELEVATION (as admin).
# !! SEE CAVEATS BELOW.
[Environment]::SetEnvironmentVariable('PATH', ($env:PATH + ";$addPath"), 'User')
That is, as Herohtar points out, the method expects only a complete, new value, as the second parameter, and its third parameter specifies the target scope for the persistent, registry-based environment-variable definition.
Caveats:
The process-level $env:PATH value is a composite value of the machine-level and user-level definitions in the registry, so with the command above you're in effect duplicating entries from the respective other scope.
Additionally, redefining the variable this way replaces any entries in the value that are defined in terms of other environment variables with the expanded, literal values.
$env:PATH contains expanded values to begin with, but even reading the unexpanded value directly from the registry won't work, because [Environment]::SetEnvironmentVariable() invariably writes the given string as a REG_SZ value (literal string) rather than as an REG_EXPAND_SZ value (string that may contain %FOO%-style references to other environment variables). Similarly, [Environment]::GetEnvironmentVariable() only reports expanded values.
A proper solution requires quite a bit of extra work, as discussed in this answer, which contains helper function Add-Path.
A pragmatic shortcut - if you're willing to accept that your registry definitions are converted to literal strings - is the following:
Read the current definition - for the target scope only - from the registry, via [Environment]::GetEnvironmentVariable()
Add to this scope-specific value and save it back to the same scope.
Additionally, you may want to add the new entry to the in-process definition of $env:PATH so that the change takes immediate effect.
Here is the solution in the context of a streamlined version of your code:
Write-Host "Installing Rust..." -ForegroundColor Cyan
$exePath = "$env:TEMP\rustup-init.exe"
Write-Host "Downloading..."
Invoke-WebRequest 'https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe' -OutFile $exePath
Write-Host "Installing..."
& $exePath -y
Remove-Item $exePath
$addPath = "$env:USERPROFILE\.cargo\bin"
$scope = 'User' # Change to 'Machine', if needed, which then requires ELEVATION.
[Environment]::SetEnvironmentVariable(
'PATH',
([Environment]::GetEnvironmentVariable('PATH', $scope) + ";$addPath"),
$scope
)
# Also update the current process' definition
$env:PATH += ";$addPath"

Reference default path in powershell script

Is there a way to call the system path if the path has been changed in the current terminal? i.e.:
$env:Path = "C:\some new path"
#some coding that requires a different path set up
$env:Path = $defaultPath #would have to define $defaultPath by calling the system default path
Use the following to reload the $env:PATH environment variable from the registry, as future sessions would see it (assuming no further relevant registry updates are made).
If your current session hasn't made any relevant registry updates, this is the same as getting the value that was in effect on session startup - barring any dynamic additions via a $PROFILE script:
$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine'),
[Environment]::GetEnvironmentVariable('Path', 'User') -join ';'
Note:
A process' effective $env:PATH value is a composite value of a machine-level and a user-level registry entry, with the machine-level definition taking precedence, as reflected in the two .NET API calls above.
Note that the underlying registry locations - HKEY_LOCAL_MACHIN\System\CurrentControlSet\Control\Session Manager\Environment and HKEY_CURRENT_USER\Environment - are REG_EXPAND_SZ registry values, i.e. they may be defined in terms of other environment variables, such as %SystemRoot% and %ProgramFiles%.
Both the .NET API calls above - using [Environment]::GetEnvironmentVariable() - and PowerShell's Get-ItemProperty and Get-ItemPropertyValue cmdlets expand (interpolate) such references and return verbatim paths - which is what new processes see by default too.
Given the above, the only way to robustly retrieve the value that was in effect at session startup time is to save it in a variable at startup time.
It's still stored in the registry so you can just query it:
Located: HKLM:\System\CurrentControlSet\Control\Session Manager\Environment
$key = "HKCU:\Environment",
"HKLM:\System\CurrentControlSet\Control\Session Manager\Environment"
(Get-ItemPropertyValue -Path $key -Name Path) -Join ';'
Querying the key using Get-ItemPropertyValue (as suggested by Mklement) will give you just the property's value.

Adding things to the user PATH | Powershell SETX Error [duplicate]

I followed this procedure in order to permanently add a path to SumatraPDF using powershell. The last few commands from the link are meant to check that the path has indeed been added.
When I access the path using the following command,
(get-itemproperty -path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path.split(';')
the result includes the path to SumatraPDF
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\System32\OpenSSH\
C:\ProgramData\chocolatey\bin
C:\texlive\2021\bin\win32
C:\Users\921479\AppData\Local\SumatraPDF
However when I access it using the following command,
($env:path).split(';')
the result does not contain the path to SumatraPDF:
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\System32\OpenSSH\
C:\ProgramData\chocolatey\bin
C:\texlive\2021\bin\win32
C:\Users\921479\AppData\Local\Microsoft\WindowsApps
Finally, actually passing sumatrapdf does not works, which indicates to me that the real path is the one accessed using the get-itemproperty command.
Why does the path set in the registry not correspond to the one set in $env:path? Is there a mistake in the procedure shown in the link I followed? How can I correct it?
I should mention I have already tried restarting the shell but it doesn't help.
Note:
See the middle section for helper function Add-Path
See the bottom section for why use of setx.exe should be avoided for updating the Path environment variable.
The procedure in the linked blog post is effective in principle, but is missing a crucial piece of information / additional step:
If you modify environment variables directly via the registry - which, unfortunately, is the right way to do it for REG_EXPAND_SZ-based environment variables such as Path - you need to broadcast a WM_SETTINGCHANGE message so that the Windows (GUI) shell (and its components, File Explorer, the taskbar, the desktop, the Start Menu, all provided via explorer.exe processes) is notified of the environment change and reloads its environment variables from the registry. Applications launched afterwards then inherit the updated environment.
If this message is not sent, future PowerShell sessions (and other applications) won't see the modification until the next logon / reboot.
Unfortunately, there's no direct way to do this from PowerShell, but there are workarounds:
Brute-force workaround - simple, but visually disruptive and closes all open File Explorer windows:
# Kills all explorer.exe processes, which restarts the Windows shell
# components, forcing a reload of the environment from the registry.
Stop-Process -Name explorer
Workaround via .NET APIs:
# Create a random name assumed to be unique
$dummyName = [guid]::NewGuid().ToString()
# Set an environment variable by that name, which makes .NET
# send a WM_SETTINGCHANGE broadcast
[Environment]::SetEnvironmentVariable($dummyName, 'foo', 'User')
# Now that the dummy variable has served its purpose, remove it again.
# (This will trigger another broadcast, but its performance impact is negligible.)
[Environment]::SetEnvironmentVariable($dummyName, [NullString]::value, 'User')
Workaround by calling the Windows API via an ad hoc-compiled P/Invoke call to SendMessageTimeout() in C#, via Add-Type:
While this is a proper solution, it invariably incurs a noticeable performance penalty due to the ad hoc-compilation the first time it is run in a session.
For details, see this blog post.
The approach in the blog post has another problematic aspect:
It retrieves the expanded environment-variable value from the registry, because that is what Get-ItemProperty and Get-ItemPropertyValue invariably do. That is, if directories in the value are defined in terms of other environment variables (e.g., %SystemRoot% or %JAVADIR%), the returned value no longer contains these variables, but their current values. See the bottom section for why this can be problematic.
The helper function discussed in the next section addresses all issues, while also ensuring that the modification takes effect for the current session too.
The following Add-Path helper function:
Adds (appends) a given, single directory path to the persistent user-level Path environment variable by default; use -Scope Machine to target the machine-level definition, which requires elevation (run as admin).
If the directory is already present in the target variable, no action is taken.
The relevant registry value is updated, which preserves its REG_EXPAND_SZ data type, based on the existing unexpanded value - that is, references to other environment variables are preserved as such (e.g., %SystemRoot%), and may also be used in the new entry being added.
Triggers a WM_SETTINGCHANGE message broadcast to inform the Windows shell of the change.
Also updates the current session's $env:Path variable value.
Note: By definition (due to use of the registry), this function is Windows-only.
With the function below defined, your desired Path addition could be performed as follows, modifying the current user's persistent Path definition:
Add-Path C:\Users\921479\AppData\Local\SumatraPDF
If you really want to update the machine-level definition (in the HKEY_LOCAL_MACHINE registry hive, which doesn't make sense with a user-specific path), add -Scope Machine, but not that you must then run with elevation (as admin).
Add-Path source code:
function Add-Path {
param(
[Parameter(Mandatory, Position=0)]
[string] $LiteralPath,
[ValidateSet('User', 'CurrentUser', 'Machine', 'LocalMachine')]
[string] $Scope
)
Set-StrictMode -Version 1; $ErrorActionPreference = 'Stop'
$isMachineLevel = $Scope -in 'Machine', 'LocalMachine'
if ($isMachineLevel -and -not $($ErrorActionPreference = 'Continue'; net session 2>$null)) { throw "You must run AS ADMIN to update the machine-level Path environment variable." }
$regPath = 'registry::' + ('HKEY_CURRENT_USER\Environment', 'HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment')[$isMachineLevel]
# Note the use of the .GetValue() method to ensure that the *unexpanded* value is returned.
$currDirs = (Get-Item -LiteralPath $regPath).GetValue('Path', '', 'DoNotExpandEnvironmentNames') -split ';' -ne ''
if ($LiteralPath -in $currDirs) {
Write-Verbose "Already present in the persistent $(('user', 'machine')[$isMachineLevel])-level Path: $LiteralPath"
return
}
$newValue = ($currDirs + $LiteralPath) -join ';'
# Update the registry.
Set-ItemProperty -Type ExpandString -LiteralPath $regPath Path $newValue
# Broadcast WM_SETTINGCHANGE to get the Windows shell to reload the
# updated environment, via a dummy [Environment]::SetEnvironmentVariable() operation.
$dummyName = [guid]::NewGuid().ToString()
[Environment]::SetEnvironmentVariable($dummyName, 'foo', 'User')
[Environment]::SetEnvironmentVariable($dummyName, [NullString]::value, 'User')
# Finally, also update the current session's `$env:Path` definition.
# Note: For simplicity, we always append to the in-process *composite* value,
# even though for a -Scope Machine update this isn't strictly the same.
$env:Path = ($env:Path -replace ';$') + ';' + $LiteralPath
Write-Verbose "`"$LiteralPath`" successfully appended to the persistent $(('user', 'machine')[$isMachineLevel])-level Path and also the current-process value."
}
The limitations of setx.exe and why it shouldn't be used to update the Path environment variable:
setx.exe has fundamental limitations that make it problematic, particularly for updating environment variables that are based on REG_EXPAND_SZ-typed registry values, such as Path:
Values are limited to 1024 characters, with additional ones getting truncated, albeit with a warning (as of at least Windows 10).
The environment variable that is (re)created is invariably of type REG_SZ, whereas Path is originally of type REG_EXPAND_SZ and contains directory paths based on other environment variables, such as %SystemRoot% and %JAVADIR%.
If the replacement value contains only literal paths (no environment-variable references) that may have no immediate ill effects, but, for an instance, an entry that originally depended on %JAVADIR% will stop working if the value of %JAVADIR% is later changed.
Additionally, if you base the updated value on the current session's $env:Path value, you'll end up duplicating entries, because the process-level $env:Path value is a composite of the machine-level and current-user-level values.
This increases the risk of running into the 1024-character limit, especially if the technique is used repeatedly. It also bears the risk of duplicate values lingering after the original entry is removed from the original scope.
While you can avoid this particular problem by retrieving the scope-specific value either directly from the registry or - invariably in expanded form - via [Environment]::GetEnvironmentVariable('Path', 'User') or [Environment]::GetEnvironmentVariable('Path', 'Machine'), that still doesn't solve the REG_EXPAND_SZ problem discussed above.
Use setx to permanently update an environment variable. Don't hack the registry.
After you invoke setx, just update the Path environment manually in the current session. Powershell: Reload the path in PowerShell

append to path for all users in windows programmatically.

I am appending to windows path in chef but it only reflects for administrator (uses to administrator to append to path)
# append dnx.exe to %PATH%
windows_path '%USERPROFILE%\\.dnx\\runtimes\\dnx-coreclr-win-x64.1.0.0-rc1-update1\\bin' do
action :add
end
Is there a command to append to path and make it available for all users of windows programmatically ?
I don't have experience with Chef, but the canonical way to add something to the PATH environment variable for all users is to append it to the variable in the machine environment rather than the user environment. In PowerShell you do it like this:
$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
$path += ';%USERPROFILE%\.dnx\runtimes\dnx-coreclr-win-x64.1.0.0-rc1-update1\bin'
[Environment]::SetEnvironmentVariable('PATH', $path, 'Machine')
If you want to merge that into a single statement it'd look somewhat like this:
[Environment]::SetEnvironmentVariable('PATH', ([Environment]::GetEnvironmentVariable('PATH', 'Machine') + ';%USERPROFILE%\.dnx\runtimes\dnx-coreclr-win-x64.1.0.0-rc1-update1\bin'), 'Machine')
However, you may not want to simply append to the variable, as that might keep adding the path to the variable over and over again. To avoid that you could do something like this:
$dir = '%USERPROFILE%\.dnx\runtimes\dnx-coreclr-win-x64.1.0.0-rc1-update1\bin'
$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine') -split ';' |
Where-Object { $_ -ne $dir }
$path += $dir
[Environment]::SetEnvironmentVariable('PATH', ($path -join ';'), 'Machine')
Edit: I just realized that [Environment]::SetEnvironmentVariable() can't be used in your case. While the method will set the variable to the string you pass into it, that string will be stored as a REG_SZ value in the registry. Which will prevent variables inside the string (like %USERPROFILE%) from being expanded when the path is looked up, kinda making the whole thing pointless.
To avoid this pitfall you must ensure that the path is stored in a REG_EXPAND_SZ value, e.g. like this:
$regkey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
Set-ItemProperty -Path $regkey -Name 'Path' -Value $path -Type ExpandString

How to set the Environment path variable ignoring the current user's path variable

I'm currently having an issue we're I'm trying to update the system path variable via powershell using the tutorial found in this link (http://blogs.technet.com/b/heyscriptingguy/archive/2011/07/23/use-powershell-to-modify-your-environmental-path.aspx), but unfortunately, it'll sometimes not do anything due to the fact that the value is already in the current user's path. Is there some way to ignore the current user's path and only set the system one?
$AddedFolder = 'C:\Directory'
$OldPath=(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path
IF ($ENV:PATH | Select-String -SimpleMatch $AddedFolder)
{
Return ‘Folder already within $ENV:PATH'
}
$NewPath=$OldPath.Trim(";")+’;’+$AddedFolder
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH –Value $NewPath
Check $OldPath instead of $env:Path then. I'd also recommend splitting the value at semicolons and checking if $AddedFolder is contained in that array, otherwise you might get false positives if a subfolder is already listed in the PATH.
if ($OldPath.Split(';') -contains $AddedFolder) {
Return 'Folder already within $ENV:PATH'
}

Resources