SETX doesn't append path to system path variable

前端 未结 7 1370
悲&欢浪女
悲&欢浪女 2020-12-23 18:49

I have tried below command to append some path to system path variable by batch-file :

setx PATH \"%PATH%;C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\"
<         


        
7条回答
  •  梦毁少年i
    2020-12-23 18:56

    WARNING!

    setx will truncate the value to 1024 characters.

    If you use it to modify PATH you might mess up your system.

    You can use this PowerShell snippet to add something to your path:

    $new_entry = 'c:\blah'
    
    $old_path = [Environment]::GetEnvironmentVariable('path', 'machine');
    $new_path = $old_path + ';' + $new_entry
    [Environment]::SetEnvironmentVariable('path', $new_path,'Machine');
    

    In case you want to not re-add an already existing entry something like this will do (see for a better version further down):

    $new_entry = 'c:\blah'
    $search_pattern = ';' + $new_entry.Replace("\","\\")
    
    $old_path = [Environment]::GetEnvironmentVariable('path', 'machine');
    $replace_string = ''
    $without_entry_path = $old_path -replace $search_pattern, $replace_string
    $new_path = $without_entry_path + ';' + $new_entry
    [Environment]::SetEnvironmentVariable('path', $new_path,'Machine');
    

    Here a newer version that I'm using now (2017-10-23). This version handles nested paths correctly. E.g. it handles the case of PATH containing "c:\tool\foo" and you want to add "c:\tool".

    Note, that this expands values that are in path and saves them back expanded. If you want to avoid this, have a look at the comment of @ErykSun below.

    $desired_entry = 'C:\test'
    
    $old_path = [Environment]::GetEnvironmentVariable('path', 'machine');
    
    $old_path_entry_list = ($old_path).split(";")
    $new_path_entry_list = new-object system.collections.arraylist
    
    foreach($old_path_entry in $old_path_entry_list) {
        if($old_path_entry -eq $desired_entry){
            # ignore old entry
        }else{
            [void]$new_path_entry_list.Add($old_path_entry)
        }
    }
    [void]$new_path_entry_list.Add($desired_entry)
    $new_path = $new_path_entry_list -Join ";"
    
    [Environment]::SetEnvironmentVariable('path', $new_path,'Machine');
    

提交回复
热议问题