3
votes

Let's say this is what my Windows system PATH looks like:

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:\WINDOWS\System32\WindowsPowerShell\v1.0\

How would I remove that very first entry and add it to the end of the list? I know you can use setx for this but I would rather do this using PowerShell.

3
Do you know the name of the variable that holds the PATH string in PowerShell? Why not do a loop to get each char of the string and copy it to $buffer1 until it gets to the first ";". After that, stop copying the chars to $buffer1 and start copying them to $buffer2 (that is, $buffer2 += $char). After the loop is done, simply set PATH to $buffer2 + $buffer1 - flen

3 Answers

5
votes
# 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')
0
votes

A quick and simple 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
-1
votes

I'm not too familiar with PowerShell scripting but I believe you can write plain C# in it. If that's so then perhaps the C# helps.

Note that there are three PATH environment variables to choose from: the one given to the process, the one given to the user and the one given 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);
}