Usando setx para anexar ao usuário PATH

Usando setx para anexar ao usuário PATH

Minha tentativa:

setx PATH "%PATH%;%~dp0"

Como faço isso sem que tudo no sistema PATH seja duplicado no usuário PATH?

Responder1

Como faço isso sem que o PATH do sistema seja duplicado no PATH do usuário?

Use a /mopção.

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

Notas:

  • /m - Defina a variável no ambiente do sistema HKLM. (O padrão é o ambiente 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.

Leitura adicional

  • Um índice AZ da linha de comando do Windows CMD- Uma excelente referência para todas as coisas relacionadas à linha cmd do Windows.
  • conjuntox- Defina variáveis ​​de ambiente permanentemente, SETX pode ser usado para definir variáveis ​​de ambiente para a máquina (HKLM) ou usuário conectado no momento (HKCU).

Responder2

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

o problema provavelmente tem mais de 20 anos:

-setx Caminho "%Caminho%;NovoCaminho"polui o caminho do usuário com o caminho do sistema.

-setx Caminho "%Caminho%;NovoCaminho" /Mpolui o caminho do sistema com o caminho do usuário.

-a poluição:vídeo

Não tenho certeza se existe uma solução nativa segura que contemple diretórios NÃO-ANSI fazendo uso exclusivo do prompt de comando.

esta é a minha tentativa!

- usando Microsoft Windows [versão 10.0.19042.868]

0- verifique os caminhos

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

dica: wmic ENVIRONMENT get *[para ver mais]

informações: um backup do registro foi realizado usando os comandos acima. os arquivos foram salvos no diretório atual.

1- backup do caminho do usuário em%USERPATH%

- os comandos pressupõem:

  • caminho não nulo;
  • caminho funcional;

- senuloounão funcionalcaminhofaça apenasetapa "2"

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

informações: há alguma poluição* no final da string.

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

- adicione '/'para ver melhor os espaços

set "USERPATH=%USERPATH%/"

informações

- remova até 15 espaços finais e remova '/'

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

informações: o número de espaços introduzidos NÃO foi consistente nos meus testes.

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

* ao lidar com caracteres invisíveis é mais fácil identificá-los convertendo-os para hexadecimais, faça:

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

dica: use 4, 5, 10, 11 (igual a nenhum) em encodehex

ver

2- definir¹²³ caminho do usuário como %USERPATH%único

setx PATH ^%USERPATH^%

feito!

¹informações: setx PATH "%USERPATH%"define a variávelvalorao invés deliteral %USERPATH%;

²informações: usar o literal é melhor, porque o comportamento se torna dinâmico em vez de estático. ou seja, ao usar o literal em vez do valor, apenas a %USERPATH%variável precisa ser alterada no futuro. enquanto que, usando o valor (ou seja, os endereços presentes dentro da variável), a %PATH%variável do usuário também deve ser atualizada mediante alteração em %USERPATH%[o que não é desejável].

³informações: métodos abaixo NÃO recomendados! funciona, mas é mais fácil cometer erros.

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

3- por enquanto é só usar%USERPATH%

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

dica: feche todos os programas, especialmente terminais, antes de continuar.

4- verifique novamente

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- confirmação visual

rundll32 sysdm.cpl,EditEnvironmentVariables

informações: o PATH do sistema só pode ser alterado se o comando anterior tiver sido lançado com privilégio administrativo;

6-DR:faça isso!/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

saúde!

Responder3

Parece que esta página pode cobrir o que você está tentando fazer: adicionando PATH com SETX ou PATHMAN ou algo mais? Ou talvez adicione mais detalhes à sua pergunta, para que possamos entender como isso é diferente. No entanto, essa página tem várias soluções para o mesmo problema ou para um problema semelhante ao que você está perguntando.

informação relacionada