Usando setx para agregar a la RUTA del usuario

Usando setx para agregar a la RUTA del usuario

Mi intento:

setx PATH "%PATH%;%~dp0"

¿Cómo hago esto sin que todo en la RUTA del sistema se duplique en la RUTA del usuario?

Respuesta1

¿Cómo hago esto sin que la RUTA del sistema se duplique en la RUTA del usuario?

Utilice la /mopción.

setx /m PATH "%PATH%;%~dp0"

Notas:

  • /m - Establecer la variable en el entorno del sistema HKLM. (El valor predeterminado es el entorno local HKCU)

setxuso

F:\test>setx /?

SetX has three ways of working:

Syntax 1:
    SETX [/S system [/U [domain\]user [/P [password]]]] var value [/M]

Syntax 2:
    SETX [/S system [/U [domain\]user [/P [password]]]] var /K regpath [/M]

Syntax 3:
    SETX [/S system [/U [domain\]user [/P [password]]]]
         /F file {var {/A x,y | /R x,y string}[/M] | /X} [/D delimiters]

Description:
    Creates or modifies environment variables in the user or system
    environment. Can set variables based on arguments, regkeys or
    file input.

Parameter List:
    /S     system          Specifies the remote system to connect to.

    /U     [domain\]user   Specifies the user context under which
                           the command should execute.

    /P     [password]      Specifies the password for the given
                           user context. Prompts for input if omitted.

    var                    Specifies the environment variable to set.

    value                  Specifies a value to be assigned to the
                           environment variable.

    /K     regpath         Specifies that the variable is set based
                           on information from a registry key.
                           Path should be specified in the format of
                           hive\key\...\value. For example,
                           HKEY_LOCAL_MACHINE\System\CurrentControlSet\
                           Control\TimeZoneInformation\StandardName.

    /F     file            Specifies the filename of the text file
                           to use.

    /A     x,y             Specifies absolute file coordinates
                           (line X, item Y) as parameters to search
                           within the file.

    /R     x,y string      Specifies relative file coordinates with
                           respect to "string" as the search parameters.

    /M                     Specifies that the variable should be set in
                           the system wide (HKEY_LOCAL_MACHINE)
                           environment. The default is to set the
                           variable under the HKEY_CURRENT_USER
                           environment.

    /X                     Displays file contents with x,y coordinates.

    /D     delimiters      Specifies additional delimiters such as ","
                           or "\". The built-in delimiters are space,
                           tab, carriage return, and linefeed. Any
                           ASCII character can be used as an additional
                           delimiter. The maximum number of delimiters,
                           including the built-in delimiters, is 15.

    /?                     Displays this help message.

NOTE: 1) SETX writes variables to the master environment in the registry.

      2) On a local system, variables created or modified by this tool
         will be available in future command windows but not in the
         current CMD.exe command window.

      3) On a remote system, variables created or modified by this tool
         will be available at the next logon session.

      4) The valid Registry Key data types are REG_DWORD, REG_EXPAND_SZ,
         REG_SZ, REG_MULTI_SZ.

      5) Supported hives:  HKEY_LOCAL_MACHINE (HKLM),
         HKEY_CURRENT_USER (HKCU).

      6) Delimiters are case sensitive.

      7) REG_DWORD values are extracted from the registry in decimal
         format.

Otras lecturas

  • Un índice AZ de la línea de comando CMD de Windows- Una excelente referencia para todo lo relacionado con la línea cmd de Windows.
  • setx- Configure las variables de entorno de forma permanente, SETX se puede usar para configurar las variables de entorno para la máquina (HKLM) o el usuario actualmente conectado (HKCU).

Respuesta2

[CMD, WMIC, HKLM, HKCU, SETX, RUTA, 2001]

El problema probablemente tenga más de 20 años:

-setx Ruta "%Ruta%;NuevaRuta"contamina la ruta del usuario con la ruta del sistema.

-setx Ruta "%Ruta%;NuevaRuta" /Mcontamina la ruta del sistema con la ruta del usuario.

-la contaminación:video

No estoy seguro de si existe una solución nativa segura que contemple directorios NO ANSI haciendo uso exclusivo del símbolo del sistema.

este es mi intento!

- usando Microsoft Windows [Versión 10.0.19042.868]

0- comprobar los caminos

echo %Path%
reg query "HKCU\Environment" /v Path
reg query "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /v Path
reg EXPORT "HKCU\Environment" UserEnvironment.reg /y
reg EXPORT "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" SystemEnvironment.reg /y
wmic ENVIRONMENT where "username='<SYSTEM>' AND name='Path'" get  variablevalue
wmic ENVIRONMENT where "username='%COMPUTERNAME%\\%USERNAME%' AND name='Path'" get  variablevalue

consejo: wmic ENVIRONMENT get *[para ver más]

información: se realizó una copia de seguridad del registro utilizando los comandos anteriores. los archivos se han guardado en el directorio actual.

1- ruta de usuario de respaldo en%USERPATH%

- los comandos presuponen:

  • ruta no nula;
  • camino funcional;

- sinuloono funcionalcaminohacer solopaso "2"

wmic ENVIRONMENT where "username='%COMPUTERNAME%\\%USERNAME%' AND name='Path'" get  variablevalue | more +1 > %temp%\userpathvalue.txt

información: hay algo de contaminación* al final de la cuerda.

set /P USERPATH=<%temp%\userpathvalue.txt

- agregar '/'para ver mejor los espacios

set "USERPATH=%USERPATH%/"

información

- elimine hasta 15 espacios finales, luego elimine '/'

set "USERPATH=%USERPATH:        /=/%"
set "USERPATH=%USERPATH:    /=/%"
set "USERPATH=%USERPATH:  /=/%"
set "USERPATH=%USERPATH: /=/%"
set "USERPATH=%USERPATH:/=%"

información: la cantidad de espacios introducidos NO fue consistente en mis pruebas.

echo %USERPATH%[checking final string]
setx USERPATH "%USERPATH%"

* cuando se trata de caracteres invisibles es más fácil identificarlos convirtiéndolos a hexadecimal, haga:

wmic ENVIRONMENT where "username='%COMPUTERNAME%\\%USERNAME%' AND name='Path'" get  variablevalue | more +1 > %tmp%\0 && set /P TEMPREADER=<%tmp%\0
echo %TEMPREADER% >%tmp%\1 && echo %TEMPREADER%/ && certutil -f -encodehex "%tmp%\1" "%tmp%\2" 11 | more +4 && type "%tmp%\2"
REM to open on notepad, type: certutil -f -encodehex "%tmp%\1" "%tmp%\2" 5 &&  cmd /C START "" /MAX notepad %tmp%\2

consejo: use 4, 5, 10, 11 (igual que ninguno) en encodehex

ver

2- establecer¹²³ ruta de usuario como %USERPATH%única

setx PATH ^%USERPATH^%

¡hecho!

¹información: setx PATH "%USERPATH%"establece la variablevaloren vez deliteral %USERPATH%;

²información: usar el literal es mejor, porque el comportamiento se vuelve dinámico en lugar de estático. es decir, al utilizar el literal en lugar del valor, sólo %USERPATH%será necesario cambiar la variable en el futuro. mientras que, al utilizar el valor (es decir, las direcciones presentes dentro de la variable), la %PATH%variable de usuario también debe actualizarse al cambiar %USERPATH%[lo cual no es deseable].

³información: ¡NO se recomiendan los siguientes métodos! Funciona, pero es más fácil cometer errores.

reg add "HKEY_CURRENT_USER\Environment" /v PATH /d ^%USERPATH^% /f
wmic ENVIRONMENT set name="PATH", variablevalue=^%USERPATH^%, username="%COMPUTERNAME%\\%USERNAME%"

3- por ahora solo uso%USERPATH%

setx USERPATH "%USERPATH%;ENTER-NEW-PATH-HERE"

consejo: cierre todos los programas, especialmente los terminales, antes de continuar.

4- volver a comprobar

echo %Path%
reg query "HKCU\Environment" /v Path
reg query "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /v Path
wmic ENVIRONMENT where "username='<SYSTEM>' AND name='path'" get  variablevalue
wmic ENVIRONMENT where "username='%COMPUTERNAME%\\%USERNAME%' AND name='path'" get  variablevalue

5- Revisión visual

rundll32 sysdm.cpl,EditEnvironmentVariables

información: la RUTA del sistema sólo se puede cambiar si el comando anterior se inició con privilegios administrativos;

6-TL;DR:¡hazlo!/or don't!

REM the commands pre-suppose
REM - non-null path;
REM - functional path;
REM if null or unfunctionl path don't progress!

reg query "HKCU\Environment" /v Path
reg query "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /v Path

reg EXPORT "HKCU\Environment" UserEnvironment.reg /y
reg EXPORT "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" SystemEnvironment.reg /y

wmic ENVIRONMENT where "username='%COMPUTERNAME%\\%USERNAME%' AND name='Path'" get  variablevalue | more +1 > %temp%\userpathvalue.txt
set /P USERPATH=<%temp%\userpathvalue.txt

set "USERPATH=%USERPATH%/"

set "USERPATH=%USERPATH:        /=/%"
set "USERPATH=%USERPATH:    /=/%"
set "USERPATH=%USERPATH:  /=/%"
set "USERPATH=%USERPATH: /=/%"
set "USERPATH=%USERPATH:/=%"

echo %USERPATH%[checking final string] && echo %USERPATH% > %tmp%\0
certutil -f -encodehex "%tmp%\0" "%tmp%\1" 11 | more +4 && type "%tmp%\1"

setx USERPATH "%USERPATH%"

setx PATH ^%USERPATH^%

echo done!

REM setx USERPATH "%USERPATH%;ENTER-NEW-PATH-HERE"

REM please close all programs

¡salud!

Respuesta3

Parece que esta página puede cubrir lo que estás intentando hacer: ¿Agregar PATH con SETX o PATHMAN o algo más? O tal vez agregue más detalles a su pregunta, para que podamos entender en qué se diferencia. Sin embargo, esa página tiene múltiples soluciones para el mismo problema o uno similar al que estás preguntando.

información relacionada