Removing lines from Windows path variable
Let's say this is what my Windows system PATH looks like:
C: \ oracle \ product \ 11.2.0 \ 32-bit \ client_1 \ bin; C: \ oracle \ product \ 11.2.0 \ 64-bit \ client_1 \ bin; C: \ WINDOWS \ system32; C: \ WINDOWS; C: \ WINDOWS \ system32 \ Wbem; C: \ WINDOWS \ system32 \ WindowsPowerShell \ v1.0 \
How can I delete this very first entry and add it to the end of the list? I know you can use setx to do this, but I'd rather do it using PowerShell.
source to share
# Split the existing path into the 1st entry and the rest.
$first, $rest = $env:Path -split ';'
# Rebuild the path with the first entry appended.
$env:Path = ($rest + $first) -join ';'
# To make this change persistent for the current user,
# an extra step is needed:
[Environment]::SetEnvironmentVariable('Path', $env:Path, 'User')
source to share
The quick and easy way:
$values = 'C:\oracle\product\11.2.0\32bit\client_1\bin;C:\oracle\product\11.2.0\64bit\client_1\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WIN DOWS\System32\WindowsPowerShell\v1.0\' -split ';' #'
$result = $values[$values.Count-1] + ';'
for($i = 1; $i -lt $values.Count-1; $i++){ $result += $values[$i] + ';' }
$result += $values[0]
$result
source to share
I'm not very good at PowerShell scripting, but I believe you can write plain C # in it. If so, maybe C #.
Note that there are three PATH environment variables to choose from: the one assigned to the process, the one presented to the user, and the one assigned to the machine itself. For the demo code below, I chose the one for the process.
var whichPath = EnvironmentVariableTarget.Process;
string path = Environment.GetEnvironmentVariable("PATH", whichPath);
string [] pathEntries = path.Split(';');
if (pathEntries.Length > 1)
{
// Initialize to the necessary length, for efficiency.
var sb = new StringBuilder(capacity: path.Length);
for(int i = 1; i < pathEntries.Length; ++i)
{
sb.Append(pathEntries[i]).Append(';');
}
sb.Append(pathEntries[0]).Append(';');
Environment.SetEnvironmentVariable("PATH", sb.ToString(), target: whichPath);
}
source to share