Windows path current user

Windows CMD: PATH Variable – Add To PATH – Echo PATH

PATH is an environment variable that specifies a set of directories, separated with semicolons ( ; ), where executable programs are located.

In this note i am showing how to print the contents of Windows PATH environment variable from the Windows command prompt.

I am also showing how to add a directory to Windows PATH permanently or for the current session only.

Cool Tip: List environment variables in Windows! Read More →

Echo Windows PATH Variable

Print the contents of the Windows PATH variable from cmd :

The above commands return all directories in Windows PATH environment variable on a single line separated with semicolons ( ; ) that is not very readable.

To print each entry of Windows PATH variable on a new line, execute:

Cool Tip: Set environment variables in Windows! Read More →

Add To Windows PATH

Warning! This solution may be destructive as Windows truncates PATH to 1024 characters. Make a backup of PATH before any modifications.

Save the contents of the Windows PATH environment variable to C:\path-backup.txt file:

Set Windows PATH For The Current Session

Set Windows PATH variable for the current session:

Set Windows PATH Permanently

Run as Administrator: The setx command is only available starting from Windows 7 and requires elevated command prompt.

Permanently add a directory to the user PATH variable:

Permanently add a directory to the system PATH variable (for all users):

Info: To see the changes after running setx – open a new command prompt.

Системная переменная окружения PATH в Windows

Если Вам нужно настроить PATH в Linux — перейдите сюда

↓ Содержание статьи ↓

Для чего используется
Пример
Добавить директорию в PATH
Изучить содержимое PATH
Ошибки
Postgesql

Для чего используется

Когда Вы выполняете какую-либо команду в консоли, система ищет соответствие между названием этой команды и программой, которую можно выполнить.

Искать по всему жёсткому диску было бы слишком долго, поэтому поиск осуществляется только по некоторым директориям.

Список этих особых директорий хранится в системной переменной PATH.

Пример

Предположим, что возникла необходимость запускать какую-то программу, например Firefox , непосредственно из командной строки.

Без предварительной подготовки ввод Firefox в консоль выдаст ошибку.

‘firefox’ is not recognized as an internal or external command, operable program or batch file.

Чтобы решить эту проблему нужно добавить директорию с испоняемым файлом firefox в PATH

Добавить директорию в PATH

Быстрый способ перейти к редактированию PATH — нажать клавишу Win и ввести в поиск env

Правый клик на Этот Компьютер (This PC) → Свойства (Properties)

Дополнительные параметры системы (Advanced system settings)

Дополнительно (Advanced) → Переменные среды (Environment Variables)

Если хотите менять для всей системы, то в окошке «Переменные среды» (System Variables) найдите строку PATH в блоке «Системные переменные» (System variables) выделите кликом и нажмите кнопку «Изменить. » (Edit. )

Если хотите менять только для своего пользователя, то делайте это в блоке «Переменные среды пользователя %USERNAME%» (User variables for %USERNAME%)

Создайте новый путь (New)

Введите адрес директории в которой лежит нужная программа. В нашем случае это

C:\Program Files (x86)\Mozilla Firefox

Перезапустите консоль или открываем новую и пишем там firefox.

Браузер должен запуститься.

Изучить содержимое PATH

В PowerShell достаточно выполнить

Name Value —- —— Path C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPo.

В cmd.exe посмотреть список переменных окружения можно выполнив команду set без параметров.

Выдача содержит системные переменные и переменные пользователя а также дополнительную информацию. Содержимое PATH выделено зелёным.

Ошибки

-bash: syntax error near unexpected token `(‘

Скорее всего Вы пытаетесь добавить в unix PATH адрес из Windows, c пробелами, скобками и так далее.

andrey@olegovich-10:/usr/share$ export PATH=/mnt/c/Program Files (x86)/Common Files/Oracle/Java/javapath_target_1128437:$PATH

-bash: syntax error near unexpected token `(‘

Для решения этой проблемы Вам нужно экранировать пробелы и скобки. Если импортируется много путей и ввод очень длинный — немного проще записать PATH=$PATH:/путь , если Вам подходит запись в конец.

Также нужно помнить, что все лишние пробелы сломают импорт — для проверки можно сделать весь скрипт в одну строку в текстовом редакторе.

Также стоит помнить, что если Вы работаете в bash под Windows , то переменные окружения нужно задавать через Windows.

andrey@olegovich-10:/usr/share$ export PATH=$PATH:/mnt/c/Program\ Files\ \(x86\)/Common\ Files/Oracle/Java/javapath_target_1128437

Postgesql

Приведу пример для использования psql из bash под Windows — это может пригодиться если Вы хотите временно добавить путь к psql в PATH чтобы запустить Postrgres скрипт.

В моём случае psql.exe находится в папке C:\Program Files\PostgreSQL\12\bin

Похожие статьи:

Если остались вопросы — смело задавайте их в Telegram группе — aofeedchat либо воспользуйтесь поиском по сайту

Чтобы следить за выходом новых статей — подписывайтесь на Telegram канал aofeed

Obtain Current Users %APPDATA% Path and not Admins

I am looking to get the path to the current users %APPDATA% folder.

Note: I am aware of the variable $APPDATA BUT if you run your installer with RequestExecutionLevel admin then $APPDATA will point to the admins roaming folder and NOT the current user’s app data folder.

I need to find out the current users %APPDATA% path so I can write files to their roaming directory. Does anyone know how I can find this out?

2 Answers 2

The term «Current User» is ambiguous, do you mean:

  • The user you get from WTSQueryUserToken() ? (WinLogon)
  • The user that the shell’s taskbar is running as? ( GetShellWindow() )
  • The user (parent process) that started your setup process?

All of those can be different users if you are having fun with runas!

The comment from Harry Johnston is spot on and once you start mixing %ProgramFiles% and %AppData% and/or HKLM and HKCU your setup is broken in multi-user scenarios. What happens when a different user starts the application? They are not going to have your files in their %AppData%.

If the addin is installed/registered in a global location you can install the AppData «template» files in %ProgramFiles%, %CommonProgramFiles% or %ALLUSERSPROFILE% and when your addin runs as a specific user for the first time you copy the files to %AppData%.

Active Setup could be used as a alternative but it will probably require a log-off/log-on cycle.

If you cannot implement the delayed copy/install for some reason you are left with hacks like the UAC plugin which gives you some access to the user that started your installer.

How do I change the User Profile location in Windows 10?

The default location for User Profiles are C:\Users . I would like to move this location to another drive (i.e. D:\Users ). I’ve already been able to customize the library locations, however there are other things that I like to migrate as well. Is there a simple way to change the default location of the User Profiles?

4 Answers 4

WARNING: Create a backup and a restore point before you try this. I messed up once and had to do a restore myself!

Requires local admin.

Move files that you want to keep from your profile somewhere independent, for example directly on the C: or D: drive

Modify the registry value of ProfilesDirectory under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList to point to your new directory. This will only come into effect for new profiles

Create a temporary user with admin rights on the local computer. This is needed to remove your domain user profile so it can be recreated.

Log out of your account and log into the temporary admin user.

Find Advanced System Settings (for example through Start | Run and typing sysdm.cpl ) and select Settings from the User Profile section.

Find the username of your domain user and click the Delete button

I recommend using Switch Accounts rather than logging out of the temporary account. That way, if something went wrong, you still have one account that’s working

Switch accounts and log in with your domain user. The profile should now be recreated in the correct location.

Windows shell command to get the full path to the current directory?

Is there a Windows command line command that I can use to get the full path to the current working directory?

Also, how can I store this path inside a variable used in a batch file?

14 Answers 14

Use cd with no arguments if you’re using the shell directly, or %cd% if you want to use it in a batch file (it behaves like an environment variable).

You can set a batch/environment variable as follows:

sample screenshot from a Windows 7 x64 cmd.exe.

Update: if you do a SET var = %cd% instead of SET var=%cd% , below is what happens. Thanks to jeb.

Quote the Windows help for the set command ( set /? ):

Note the %CD% — expands to the current directory string. part.

This has always worked for me:

For Windows we can use

command is there.

For Windows, cd by itself will show you the current working directory.

For UNIX and workalike systems, pwd will perform the same task. You can also use the $PWD shell variable under some shells. I am not sure if Windows supports getting the current working directory via a shell variable or not.

On Windows:

CHDIR Displays the name of or changes the current directory.

In Linux:

PWD Displays the name of current directory.

Based on the follow up question (store the data in a variable) in the comments to the chdir post I’m betting he wants to store the current path to restore it after changeing directories.

The original user should look at «pushd», which changes directory and pushes the current one onto a stack that can be restored with a «popd». On any modern Windows cmd shell that is the way to go when making batch files.

If you really need to grab the current path then modern cmd shells also have a %CD% variable that you can easily stuff away in another variable for reference.

Читайте также:  Windows 10 ошибка при создании пользователя
Оцените статью