- PATH – отобразить или изменить пути поиска исполняемых файлов.
- Set path from command line
- How to set path from command line?
- Add directory to system path environment variable:
- Default option is not allowed more than ‘2’ time(s)
- How do you find the current user in a Windows environment?
- 15 Answers 15
- PowerShell
- Not the answer you’re looking for? Browse other questions tagged windows batch-file or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Windows cmd user path
- Синтаксис
- Параметры
- Примечания
- Примеры
PATH – отобразить или изменить пути поиска исполняемых файлов.
Команда PATH используется для указания или просмотра путей поиска исполняемых файлов. Пути поиска представляют собой строки, определяющие перечень каталогов файловой системы, в которых находятся исполняемые файлы (файлы с расширением .bat, .cmd, .exe, .vbs и т.п. ), разделенные точкой с запятой ; Например, C:\windows;C:\windows\system32 — определяет пути поиска C:\windows и C:\windows\system32 . Если вы в командной строке набираете program.exe без явного указания пути, то для запуска файла program.exe выполняется его поиск в текущем каталоге, и если он не найден, то в каталоге C:\windows , если и там не найден – в каталоге C:\windows\system32 . Если же исполняемый файл будет в обоих каталогах, то выполнится запуск из того, что определен ранее — C:\windows . Значение переменной среды PATH содержит пути поиска исполняемых файлов определенный на данный момент времени.
Формат командной строки:
PATH ; — очистить путь поиска используемых файлов, ограничив его текущим каталогом.
PATH [[диск:]путь[;. ][;] — установит ь пути поиска исполняемых файлов.
Команда PATH без параметров отображает текущий путь поиска. В командную строку допускается включение переменной %PATH% , задающей прежний путь поиска.
path /? — отобразить подсказку по использованию команды.
path — отобразить пути поиска исполняемых файлов.
path %PATH%;C:\Scripts — добавить путь C:\Scripts в конец существующего списка каталогов для поиска исполняемых файлов.
path C:\scripts;%PATH% — добавить путь C:\Scripts в начало существующего списка каталогов для поиска исполняемых файлов.
При выполнении команды PATH, значение передаваемых ей параметров не анализируется и воспринимается как обычная строка символов, поэтому, например, трижды выполнив команду path C:\scripts;%PATH% вы создадите 3 записи для пути C:\Scripts . Значение переменной PATH, измененное командой действует только на момент текущего сеанса командной строки. Для постоянного изменения системных и пользовательских переменных среды, в том числе, и путей поиска, используется команда SetX . В постоянно действующих путях поиска не стоит указывать каталоги сменных носителей (дискет, CD/DVD, карты памяти и т.п.)
Set path from command line
Users can run an executable from windows command prompt either by giving the absolute path of the file or just by the executable file name. In the latter case, Windows searches for the executable in a list of folders which is configured in environment variables. These environment variables are as below.
1. System path
2. User path
The values of these variables can be checked in system properties( Run sysdm.cpl from Run or computer properties). Initially user specific path environment variable will be empty. Users can add paths of the directories having executables to this variable. Administrators can modify the system path environment variable also.
How to set path from command line?
In Vista, Windows 7 and Windows 8 we can set path from command line using ‘setx’ command.
For example, to add c:\dir1\dir2 to the path variable, we can run the below command.
Alternative way is to use Windows resource kit tools ‘pathman.exe‘. Using this command we can even remove a directory from path variable. See download windows resource kit tools. This works for Windows 7 also.
Add directory to system path environment variable:
Open administrator command prompt
Run the below command
Remove path from system path environment variable:
Run the below command from elevated command prompt
Setting user path environment variable
For user environment varlables, admin privileges are not required. We can run the below command to add a directory to user path environment variable.
To remove a directory from user path, you can run the below command.
Default option is not allowed more than ‘2’ time(s)
You get this error if you have not enclosed ‘path’ in double quotes. See the below example for setting the path of firefox.
Now if you move %path% to be in the double quotes
Could a context entry be created for folders, perhaps an extended one… to add to path?
what about a multi-verb option, like copy as path?
hi, when i use setx at an administrator command line, it creates a USER variable, NOT the SYSTEM variable. What am i doing wrong? How do i change the SYSTEM path at command prompt? -thx
Johny Why
Answer: Try add the parameter /M
Hi, is there a way I can add an extra variable instead on deleting the currently one and put a new Variable on the Path.
I used the command setx /M “c:\Options”, and what it does is delete the current one and then puts that one there, all I want is to add the new variable to the current one. -thx
Nuno, pathman described above does exactly that. You can download the resource tools kit and get it.
setx path “%path%;C:\yourFolder”
To set path for java & javac, can I add the paths to PATH or do I need to create the environment variable JAVA_HOME. I don’t have this defined, but windows does not seem to be able to find java binaries on my system.
You can directly add the folder to PATH. No need to define JAVA_HOME. However, adding JAVA_HOME separately avoids cluttering and helps to easily understand what is added.
hello, can someone plz explain this result? After setting path, it did not change. This was run from an Administrator command-line:
C:\Windows\system32>setx path “C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin”
SUCCESS: Specified value was saved.
C:\Windows\system32>path
PATH=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\ProgramData\chocolatey\bin;D:\Program Files (x86)\Microsoft VS Code\bin;D:\Program Files (x86)\metapad36;D:\Program Files (x86)\metapad36″ /M
Why won’t this work?
SET EPO = D:\Program Files (x86)\McAfee\ePolicy Orchestrator
PATH = %PATH%;%EPO%\jre\bin;%EPO%\apache2\bin
In windows 10 set path %path%; not working. it’s work like :
setx “%path%;C:\Program Files\CodeBlocks\MinGW\bin”
By unfortunately I deleted my system default path. How could I able to find my system path?
Unfortunately I deleted several files with unremembered path names. This article was useful
The following used to work for me when I am in MSDOS environment. Lately I get error messages such as INCLUDE not found. Why is this so?
Used to work
SET PLL =c:\CL5\PLL
SET PLT =c:\CL5\PLL
SET INCLUDE =c:\CL5\INCLUDE
SET PRG =c:\IMS\PRG
SET LIB =c:\CL5\LIB
SET OBJ =c:\CL5\OBJ
PATH =c:\IMS\EXE;\CL5\BIN;\CL5\NG;\CL5\PLL
pathman is one of many tools of the Windows Server 2003 Resource Kit Tools
Note: The Windows Server 2003 Resource Kit Tools are not supported on 64-bit platforms.
Huh.
When I did that on Windows 10 v1903, using setx, it replaced the USER scope paths with the SYSTEM scope paths.
Now I’m not sure what was in the old user path.
So, uh… Be careful out there.
And if anyone has a solution how to avoid that, please let me know
Thanks
How do you find the current user in a Windows environment?
When running a command-line script, is it possible to get the name of the current user?
15 Answers 15
You can use the username variable: %USERNAME%
Username:
Domainname:
You can get a complete list of environment variables by running the command set from the command prompt.
Just use this command in command prompt
It should be in %USERNAME% . Obviously this can be easily spoofed, so don’t rely on it for security.
Useful tip: type set in a command prompt will list all environment variables.
%USERNAME% is the correct answer in batch and other in Windows environments.
Another option is to use %USERPROFILE% to get the user’s path, like C:\Users\username .
The answer depends on which «command-line script» language you are in.
In the old cmd.exe command prompt or in a .bat or .cmd script, you can use the following:
%USERNAME% — Gets just the username.
%USERDOMAIN% — Gets the user’s domain.
PowerShell
In the PowerShell command prompt or a .ps1 or .psm1 script, you can use the following:
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name — Gives you the fully qualified username (e.g. Domain\Username). This is also the most secure method because it cannot be overridden by the user like the other $Env variables below.
$Env:Username — Gets just the username.
$Env:UserDomain — Gets the user’s domain.
$Env:ComputerName — Gets the name of the computer.
%USERNAME% will get you the username of the currently running process. Depending on how you are running your batch file, this is not necessarily the same as the name of the current user. For example, you might be running your batch file through a scheduled task, from a service, etc.
Here is a more sure way of getting the username of the currently logged on user by scraping the name of the user that started the explorer.exe task:
I use this method in writing batch files for testing.
Since you must include the password in plain text if authentication is required, I will only use it in a completely private environment where other users cannot view it or if a user seeing the password would bear no consequences.
Hope this helps someone out.
It’s always annoyed me how Windows doesn’t have some of more useful little scripting utilities of Unix, such as who/whoami, sed and AWK. Anyway, if you want something foolproof, get Visual Studio Express and compile the following:
And just use that in your batch file.
In most cases, the %USERNAME% variable will be what you want.
However, if you’re running an elevated cmd shell, then %USERNAME% will report the administrator name instead of your own user name. If you want to know the latter, run:
Just type whoami in command prompt and you’ll get the current username.
This is the main difference between username variable and whoami command:
In a standard context, each connected user holds an explorer.exe process: The command [tasklist /V|find «explorer»] returns a line that contains the explorer.exe process owner’s, with an adapted regex it is possible to obtain the required value. This also runs perfectly under Windows 7.
In rare cases explorer.exe is replaced by another program, the find filter can be adapted to match this case. If the command return an empty line then it is likely that no user is logged on. With Windows 7 it is also possible to run [query session|find «>»].
As far as find BlueBearr response the best (while I,m running my batch script with eg. SYSTEM rights) I have to add something to it. Because in my Windows language version (Polish) line that is to be catched by «%%a %%b»==»User Name:» gets REALLY COMPLICATED (it contains some diacritic characters in my language) I skip first 7 lines and operate on the 8th.
Via powershell (file.ps1) I use the following
It returns the name of the user in the «Domain\Username» format. If you just want the username just write
The advantage is that It works with windows 10 windows 8 server 2016. As far as I remember with also other OS like Win7 etc. (not older) . And yeah via batch you can simply use
Not the answer you’re looking for? Browse other questions tagged windows batch-file or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Windows cmd user path
Устанавливает путь поиска в переменной среды PATH, которая является набором каталогов, используемых для поиска исполняемых файлов. Вызванная без параметров, команда path выводит текущий путь поиска.
Синтаксис
path [[%path%] [диск:]путь [;. ]]
Параметры
Примечания
- Использование значения ;
Если ; используется в качестве самостоятельного параметра, то происходит удаление существующего пути поиска, найденного в переменной PATH.
Использование %path%
Если параметр %path% включен в синтаксис, то командный интерпретатор Cmd.exe заменяет его на значение пути поиска, найденное в переменной PATH, устраняя тем самым необходимость ручного ввода этих значений в командной строке. Сведения о замене значений переменных среды см.в разделе «Командная оболочка: обзор» в «См.Также».
Операционная система всегда начинает поиск с текущего каталога, а затем продолжает его в каталогах, заданных в пути поиска.
Файлы с одинаковыми именами и разными расширениями
В некоторых случаях в одном каталоге могут содержаться файлы с одинаковыми именами, но с разными расширениями. Например, файл Accnt.com, запускающий бухгалтерскую программу, и файл Accnt.bat, выполняющий подключение к бухгалтерской сети.
Поиск файлов происходит с учетом их расширений в следующем порядке:.exe, .com, .bat и .cmd. Чтобы запустить файл Accnt.bat (при наличии в том же каталоге файла Accnt.com), необходимо в командной строке указать его расширение (.bat).
Два или более одинаковых имен файлов в пути поиска
Если в пути поиска указаны два или более файлов с одинаковыми именами и расширением, то Windows XP сначала осуществляет поиск указанного имени в текущем каталоге, а затем уже в каталогах пути поиска в том же порядке, в котором они перечислены в PATH.
Поиск подсистемы MS-DOS
Если команда path включена в файл Autoexec.nt, то при каждом входе в систему она будет автоматически добавлять заданный путь поиска подсистемы MS-DOS к пути поиска Windows XP. Интерпретатор команд Cmd.exe не использует файл Autoexec.nt. При запуске из ярлыка Cmd.exe наследует набор переменных среды из My Computer/Properties/Advanced/Environment.
Примеры
Приведенная ниже команда задает использование Windows XP для поиска трех каталогов для нахождения внешних команд. Пути для этих трех каталогов следующие: C:\User\Taxes, B:\User\Invest и B:\Bin: