In fact, I wrote this print environment variables in PowerShell tutorial after getting annoyed from echo and set commands output. Additionally, You can see readability issue with the list all environment variables from the command line tutorial outputs.
Print Environment Variables in PowerShell
Specifically, You will love the strength of PowerShell when writing PowerShell scripts or small code snippets. To illustrate, I am writing few example commands that you can use in PowerShell to list all environment variables.
Environment Variable in PowerShell
Firstly, You can use $env: variable in PowerShell to list all environment variables in PowerShell. Further, You cannot use echo %PATH%
command in PowerShell because it will only display %PATH% in console. Of course, we have different PowerShell syntax to display environment variables paths, here is the command.
echo $env:Path
Of course, you can ask that what is the difference between Command Prompt and PowerShell output? Well, I displayed the results before formatting the output.
Split Semicolon Separated String with PowerShell
Let’s start to check the power of PowerShell and I am using Windows PowerShell ISE for easiness. Similarly, You can see the below output from the echo $env:Path.Split(";")
command.
$env:Path.Split(";")
PowerShell Commands to List Environment Variables
Further, I am writing few other PowerShell commands to list environment variables.
echo $env:Path Command
Firstly, You can use the echo command in PowerShell but I called it extra code because you can directly print the variables in PowerShell.
echo $env:Path
Get-Item env:Path Command
Secondly, If you are coding lover and love to write more code to do the task, you can use Get-Item env:Path Command for this.
Get-Item Env:\Path | ForEach-Object { $name = $_.Name $_.Value -split ';' | Where-Object { $_ } | Select-Object @{n="Name";e={$name}}, @{n="Value";e={$_}} }
Get-ChildItem env:Path Command
Thirdly, You can use Get-ChildItem env:Path Command command to do the same but with some extra code. You will find it similar to Get-Item env:Path Command.
Get-ChildItem Env:\Path | ForEach-Object { $name = $_.Name $_.Value -split ';' | Where-Object { $_ } | Select-Object @{n="Name";e={$name}}, @{n="Value";e={$_}} }
Variables in PowerShell
Additionally, you can see that we used dollar sign ($) as our starting command, it is called variable in PowerShell.
- How do I get and print value of an environment variable?
- Print Environment Variables in Windows PowerShell
- 2 ways to List environment variables in command line windows
- PowerShell – Print Environment Variables
- Print Single or All Environment Variables With GitHub Actions
- Windows: List Environment Variables – CMD & PowerShell
- How to Set Environment Variable in Windows
- How to Setup System Environment Variables in Windows?
How do I get and print value of an environment variable?
I want to print value from a Windows environment variable, say, path or
errorlevel, I’ve tried this but it doesn’t work. Connect and share knowledge
within a single location that is structured and easy to search. 4 I want to
print value from a Windows environment variable, say, path or errorlevel, I’ve
tried this but it doesn’t work
echo %PATH
%PATH
PATH=$(PATH);\nonesuch
all:
echo %PATH%
nmake /E
echo %%PATH%%
"echo %PATH%"
echo $(PATH)
echo $PATH
Print Environment Variables in Windows PowerShell
Printing All Environment Variables Using the Get-ChildItem Command. We can use
the Get-ChildItem cmdlet to output all environment variables to the command-
line interface. Since the Get-ChildItem cmdlet is a native PowerShell command,
we can use it with …
$env:PATH
C:\Windows\system32;C:\Windows;C:\Users\user01\AppData\Local\Microsoft\WindowsApps;
Get-ChildItem Env:
Get-ChildItem Env: | Select Name | Export-Csv -Path C:\env_variables.txt -NoTypeInformation
Get-ChildItem Env:APPDATA
Get-Alias -Definition Get-ChildItem
CommandType Name Version Source
----------- ---- ------- ------
Alias dir -> Get-ChildItem
Alias gci -> Get-ChildItem
Alias ls -> Get-ChildItem
dir env:
gci env: | select name
ls env:ALLUSERSPROFILE | Export-Csv -Path C:\env_variables.txt -NoTypeInformation
2 ways to List environment variables in command line windows
with > and set command, It prints the list to the output file. Here is an
example of usage. C:\>set > output.txt. This will output the environment
variables list to the output.txt file. Please note that administration
permission is required to run this command, Otherwise, it gives Access is
denied. If you want to filter the list, you can use
set VARIABLE=path/value
set JAVA_HOME=c:\JDK1.9
C:\>set
ALLUSERSPROFILE=C:\ProgramData
ANDROID_HOME=A:\android\sdk
ANT_HOME=A:\Java\apache-ant-1.10.0
APPDATA=C:\Users\Kiran\AppData\Roaming
ChocolateyInstall=C:\ProgramData\chocolatey
ChocolateyLastPathUpdate=132329753418192180
ChocolateyToolsLocation=C:\tools
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=KIRAN
ComSpec=C:\WINDOWS\system32\cmd.exe
DERBY_HOME=C:\db-derby-10.14.2.0-bin
DriverData=C:\Windows\System32\Drivers\DriverData
GOOGLE_API_KEY=no
set | more
C:\>set > output.txt
C:\>set derby
DERBY_HOME=C:\db-derby-10.14.2.0-bin
Get-ChildItem Env:
PowerShell – Print Environment Variables
Environment variable in Windows operating system stores that is used by
programs. Using PowerShell, we can print environment variables on the console.
In the above post, I explained how to use different PowerShell commands like
dir env: , gci env: , ls env:, and Get-ChildItem to print environment
variables on console or output to file as well.
dir env:
gci env:
ls env:
$env:APPDATA
gci env: | sort-object name| Export-Csv -Path D:\env_variables.txt -NoTypeInformation
Get-ChildItem Env: | Sort Name
Get-ChildItem Env:APPDATA
Print Single or All Environment Variables With GitHub Actions
In the last line of the workflows, we are printing all the environment
variables available on a Ubuntu runner. Note: To print all the environment
variables on a Windows runner, change the runs-on to windows-latest. name:
Print a single or all environment variables on: push jobs: build: runs-on:
ubuntu-latest steps: — name: Check out repo uses
name: Print a single or all environment variables
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Check out repo
uses: actions/[email protected]
- run: echo " Print a single environment variable (the commit SHA ) - ${{ github.sha }} "
- run: echo "Print all environment variables"
- run: env
Windows: List Environment Variables – CMD & PowerShell
An environment variable is a dynamic “object” containing an editable value
which may be used by one or more software programs in Windows. In this note i
am showing how to list environment variables and display their values from the
Windows command-line prompt and from the PowerShell. Cool Tip: Add a directory
to Windows %PATH% environment
C:\> set
C:\> echo %ENVIRONMENT_VARIABLE%
PS C:\> gci env:* | sort-object name
PS C:\> echo $env:ENVIRONMENT_VARIABLE
How to Set Environment Variable in Windows
Set Environment Variable in Windows via GUI. Follow the steps to set
environment variables using the Windows GUI: 1. Press Windows + R to open the
Windows Run prompt. 2. Type in sysdm.cpl and click OK. 3. Open the Advanced
tab and click on the Environment Variables button in the System Properties
window. 4.
set
Get-ChildItem Env:
echo %[variable_name]%
echo $Env:[variable_name]
setx [variable_name] "[variable_value]"
setx Test_variable "Variable value"
setx [variable_name] "[variable_value]" /M
reg query HKEY_CURRENT_USEREnvironment
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
reg query HKEY_CURRENT_USEREnvironment /v [variable_name]
reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name]
reg delete HKEY_CURRENT_USEREnvironment /v [variable_name] /f
reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name] /f
setx [variable_name] trash
How to Setup System Environment Variables in Windows?
Steps for Windows 10. Go to settings and enter the “About” menu. Now go to
“Advanced system settings.”. The System Properties dialogue box should appear
on your screen. Click on the “Advanced” tab and select “Environment
Variables.”. Windows 10 will now display the entire list of user and system
variables stored on your computer.
rundll32.exe sysdm.cpl,EditEnvironmentVariables
setx [variable_name] “[variable_value]”
setx [TEST_VARIABLE] “[XYZ]”
Get-ChildItem Env:
[Environment]::GetEnvironmentVariables("Machine")
[Environment]::GetEnvironmentVariables("User")
$env:Variable_name = 'Variable_value'
$env:TEST_VARIABLE = '[ABC]'
$env:TEST_VARIABLE
$env:Variable_name = ';Variable_value2'
Настройка переменных среды Windows может помочь сократить время, необходимое для набора команд в командной строке или, если вы часто пишете скрипты для собственных задач, сделать их более читаемыми. В большинстве случаев обычные пользователи добавляют записи в системную переменную среды PATH, хотя бывают и другие задачи.
В этой пошаговой инструкции базовая информация о том, как открыть переменные среды Windows 11 и Windows 10, создать или отредактировать их.
Что такое переменные среды
Переменные среды в Windows — записи о расположении системных папок, свойствах системы и другие, которые доступны для любой программы или скрипта.
Одна из наиболее часто используемых переменных среды — PATH, указывающая на папки, в которых выполняется поиск файлов, вызываемых в командной строке, терминале Windows, файле bat или из других источников. В качестве примера её назначения:
- Если вы откроете командную строку (или диалоговое окно «Выполнить»), введёте regedit и нажмете Enter — вы сможете запустить редактор реестра, не указывая полный путь к файлу regedit.exe, поскольку путь C:\Windows добавлен в переменную среды Path.
- Если же тем же образом в командной строке написать имя программы, путь к которой не добавлен в Path (chrome.exe, adb.exe, pip и другие), вы получите сообщение «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом».
Если предположить, что вы часто используете команды adb.exe (например, для установки приложений Android в Windows 11), pip install (для установки пакетов Python) или любые другие то для того, чтобы не писать каждый раз полный путь к этим файлам, имеет смысл добавить эти пути в переменные среды.
Также вы можете добавлять и иные переменные среды (не обязательно содержащие пути), а в дальнейшем получать и использовать их значения в сценариях BAT (командной строки) или PowerShell. Пример получения и отображения значения системной переменной PATH для обоих случаев:
echo %PATH% echo $Env:PATH
Получить список всех переменных среды в командной строке и PowerShell соответственно можно следующими командами:
set ls env:
Редактирование переменных среды Windows 11/10
Прежде чем приступать, учтите: изменение системных переменных среды по умолчанию может привести к проблемам в работе системы, не удаляйте уже имеющиеся переменные среды. Возможно, имеет смысл создать точку восстановления системы, если вы не уверены в своих действиях.
- Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter.
- На вкладке «Дополнительно» нажмите кнопку «Переменные среды…»
- В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»).
- Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы.
- Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой».
- При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.
После создания или изменения переменной среды и сохранения сделанных настроек, переменная или обновленные значения сразу становятся доступны для текущего пользователя или в системе в целом в зависимости от того, какие именно переменные редактировались или создавались. Также есть методы добавления переменных среды в командной строке или PowerShell, подробнее в статье: Как добавить путь в переменную среды PATH
- How do I show the path in PowerShell?
- What is Env path in PowerShell?
- How do I see environment variables in PowerShell?
- How do you echo path?
- How do I start PowerShell in a specific directory?
- What is PATH environment variable?
- What does split path do in PowerShell?
- How do I access environment variables?
- Where are PowerShell variables stored?
- What is $_ in PowerShell?
- How do I get command history in PowerShell?
- How do I echo in PowerShell?
- What is path command?
- How do you echo a variable in PowerShell?
How do I show the path in PowerShell?
List $Env:Path with PowerShell. You can also see path values in the Control Panel; navigate to the System section and then click on the link to ‘Advanced system settings’. Our purpose is employing PowerShell to list these paths. Remember that we are dealing with an Environmental Variable, hence $Env.
What is Env path in PowerShell?
The Windows PATH environment variable is where applications look for executables — meaning it can make or break a system or utility installation. Admins can use PowerShell to manage the PATH variable — a process that entails string manipulation. To access the PATH variable, use: $env:Path.
How do I see environment variables in PowerShell?
Windows environment variables are visible as a PS drive called Env: To list all the environment variables use: Get-Childitem env: (or just dir env:)
How do you echo path?
To print the entire path, use echo %path% . This will print all directories on a single line separated with semicolons ( ; ) To search / replace a string in a variable, use %path:a=b% which will replace all a characters with b. echo. is used to print a newline.
How do I start PowerShell in a specific directory?
Open File Explorer and navigate to the folder/location you want to open PowerShell in. In the address bar, type ‘powershell’ and hit Enter. Give it a second and a PowerShell window will open at that location. You can do the same for Command Prompt.
What is PATH environment variable?
PATH environment variable
An environment variable is just a named value that can be referenced by your operating environment. … The way that PATH is used is that any executable files in the directories listed in PATH can be executed without specifying the full path to the file.
What does split path do in PowerShell?
The Split-Path cmdlet returns only the specified part of a path, such as the parent folder, a subfolder, or a file name. It can also get items that are referenced by the split path and tell whether the path is relative or absolute. You can use this cmdlet to get or submit only a selected part of a path.
How do I access environment variables?
On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables.
Where are PowerShell variables stored?
In PowerShell, environment variables are stored in the Env: «drive», accessible through the PowerShell environment provider, a subsystem of PowerShell. This isn’t a physical drive, but a virtual file system.
What is $_ in PowerShell?
$_ in the PowerShell is the ‘THIS’ toke. It refers to the current item in the pipeline. It can be considered as the alias for the automatic variable $PSItem.
How do I get command history in PowerShell?
Using the F8 key, you can find the command in history that matches the text on the current command line. For example, enter get- and press F8 . The last entry in the command history matching this text will be found. To go to the next command in history, press F8 again.
How do I echo in PowerShell?
The echo command is used to print the variables or strings on the console. The echo command has an alias named “Write-Output” in Windows PowerShell Scripting language. In PowerShell, you can use “echo” and “Write-Output,” which will provide the same output.
What is path command?
The path command specifies the location where MS-DOS should look when it executes a command. For example, if you were to use the «format» command, the path must be specified, or you will receive the message «bad command or file name.» See our path definition for a full explanation and examples of paths on computers.
How do you echo a variable in PowerShell?
Use Write-Output as echo Equivalent in PowerShell
The closest echo equivalent is Write-Output . echo is the built-in alias for Write-Output . The Write-Output writes output data to the pipeline and allows you to redirect the output to another command or file.
Reading Environment Variables
To read an environment variable in PowerShell, you can use the $env
prefix. For example, to read the Path
environment variable, use the following command:
$Mavariable = $env:Path echo $Mavariable
This command assigns the value of the Path
environment variable to the variable $Mavariable
and then prints it to the console.
Writing Environment Variables
To write an environment variable that will only last for the duration of the current PowerShell session, use the following syntax:
This command temporarily sets the Path
environment variable to c:\windows
. The change will be discarded when you close the PowerShell session.
Writing Permanent Environment Variables
To permanently set an environment variable, use the [Environment]::SetEnvironmentVariable
method. This method requires three parameters: the name of the variable, the value to set, and the target scope (User
or Machine
).
For example, to permanently set the Path
environment variable for the entire machine, use the following command:
[Environment]::SetEnvironmentVariable("Path", "c:\windows", "Machine")
This command updates the Path
environment variable and makes the change permanent across all sessions and users on the machine.
Example Script
Here is an example PowerShell script that reads the current Path
variable, temporarily updates it, and then sets it permanently:
# Read the current Path variable $currentPath = $env:Path echo "Current Path: $currentPath" # Temporarily set the Path variable $env:Path = "c:\temporary" echo "Temporary Path: $env:Path" # Permanently set the Path variable [Environment]::SetEnvironmentVariable("Path", "c:\windows", "Machine") echo "Permanent Path set to c:\windows"
Save this script as a .ps1
file and run it in PowerShell to see the changes in action.