С помощью PowerShell вы можете получать, добавлять, удалять, или изменять значения переменных окружения (среды). В переменных окружения Windows хранит различную пользовательскую и системную информацию (чаще всего это пути к системным и временным папкам), которая используется операционной системой и приложениями, установленными на компьютере.
В Windows доступны несколько типов переменных окружения:
- Переменные окружения процесса – создаются динамически и доступны только в текущем запущенном процесс
- Пользовательские переменные окружения – содержат настройки конкретного пользователя и хранятся в его профиле (хранятся в ветке реестре
HKEY_CURRENT_USER\Environment
) - Системные переменные окружения – глобальные переменные окружения, которые применяются для все пользователей (хранятся в ветке
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
)
Типы переменных окружения Windows указаны в порядке уменьшения приоритета. Т.е. значение переменной окружения %TEMP% в пользовательском профиле будет иметь больший приоритет, чем значение системной переменной окружения %TEMP%.
Для управления переменными окружениями обычно используется вкладка Advanced в свойствах системы. Чтобы открыть System Properties, выполните команду
SystemPropertiesAdvanced
и нажмите на кнопку Environment Variable.
В этом окне можно создать и отредактировать переменные среды для текущего пользователя или системные переменные окружения.
Чтобы вывести полный список переменных окружения и их значения в PowerShell, выполните команду:
Get-ChildItem Env:
Как вы видите, для доступа к переменным окружения в PowerShell используется отдельный виртуальный диск Env:, доступный через провайдер Environment.
Получить значение определенной переменной окружения Path:
Get-ChildItem env:Path
Т.к. переменные окружения, по сути, это файлы на виртуальном диске, нажатием кнопки TAB вы можете использовать автозавершение для набора имени переменной окружения.
Чтобы разбить значение переменной окружения на строки, выполните:
(Get-ChildItem env:Path).value -split ";"
Добавить значение в переменную окружения Path:
$Env:Path += ";c:\tools"
Однако это добавляет временное значение в переменную окружения
Path
. При следующей перезагрузке новое значение в переменной будет сброшено. Чтобы добавить постоянное значение в системную переменную окружения, используется такая конструкция:
$path = [System.Environment]::GetEnvironmentVariable("Path","Machine")
[System.Environment]::SetEnvironmentVariable("Path", $path + ";C:\tools", "Machine")
[System.Environment]::GetEnvironmentVariable("Path","Machine") -Split ";"
Чтобы изменить пользовательскую переменную окружения, замените в предыдущих командах область Machine на User.
Несмотря на то, что фактически переменные окружения и их значения хранятся в реестре, прямое изменение их значений в реестре используется редко. Причина в том, что текущий процесс при запуске считывает значение переменных окружения из реестра. Если вы измените их, процесс не будет уведомлён об этом.
Если вам нужно из PowerShell изменить в реестре значение переменной окружения, используются команды:
$variable = Get-ItemPropertyValue -Path 'HKCU:\Environment\' -Name 'Path'
$add_path = $variable + ';C:\Git\'
Set-ItemProperty -Path 'HKCU:\Environment\' -Name 'Path' -Value $add_path
Вы можете создать локальную переменную окружения. По умолчанию такая переменная окружения будет доступна только в текущем процессе (PowerShell), из которого она создана. После того, как процесс будет закрыт – переменная окружения будет удалена.
$env:SiteName = 'winitpro.ru'
Get-ChildItem Env:SiteName
Если нужно создать глобальную системную переменную (нужны права администратора), используйте команду:
[System.Environment]::SetEnvironmentVariable('siteName','winitpro.ru',"Machine")
Очистить и удалить глобальную переменную окружения:
[Environment]::SetEnvironmentVariable('siteName', $null, "Machine")
Using PowerShell to set Windows environment variables, read environment variables and create new environment variables is easy once you know the trick. The tricks you learn in this article will work for Windows 10 environment variables as well as any Windows client/server after Windows 7 SP1/Windows Server 2008.
Not a reader? Watch this related video tutorial!
Not seeing the video? Make sure your ad blocker is disabled.
PowerShell provides many different ways to interact with Windows environment variables from the $env:
PSDrive. the registry, and the [System.Environment]
.NET class. You’ll learn about each method including understand environment variable scope in this step-by-step walkthrough.
Assumptions
Throughout this article, I’ll be using Windows PowerShell 5.1 on Windows 10. But if you have any version of Windows PowerShell later than v3 on Windows 7 SP1 or later, the techniques I’m about to show you should work just fine.
What are Environment Variables?
Environment variables, as the name suggests, store information about the environment that is used by Windows and applications. Environment variables can be accessed by graphical applications such as Windows Explorer and plain text editors like Notepad, as well as the cmd.exe and PowerShell.
Using environment variables helps you to avoid hard-coding file paths, user or computer names and much more in your PowerShell scripts or modules.
Common Environment Variables
As you begin to learn more about how to work with environment variables in PowerShell, you’ll come across many different variables. Some are more useful than others. Below is a list of some of the common environment variables and their usage for reference.
Variable | Usage |
---|---|
ClientName | The name of the remote computer connected via a Remote Desktop session. |
SessionName | This helps to identify if the current Windows session is regarded by the operating system as running at the console. For console sessions SessionName will be ‘Console’. Enhanced Session connections to Hyper-V Virtual Machines do not report SessionName as ‘Console’, whereas Standard Sessions do. |
ComputerName | The name of the computer. |
SystemRoot and Windir | The path to the current Windows installation. |
ProgramFiles and ProgramFiles(x86) | The default locations for x64 and x86 programs. |
ProgramW6432 | The default location for programs, avoiding 32/64 bit redirection. This variable only applies for 32 bit processes running on a 64 bit platform. This means that you can use it to identify when a 32 bit instance of PowerShell is running on a 64 bit system. |
UserDNSDomain | The Fully Qualified Domain Name of the Active Directory domain that the current user logged on to. Only present for domain logons. |
UserDomain | The NETBIOS-style name of the domain that the current user logged on to. Can be a computer name if there’s no domain. |
UserDomainRoamingProfile | The location of the central copy of the roaming profile for the user, if any. Only present for domain logons. |
UserName | The name of the currently logged on user. |
UserProfile | The location of the profile of the current user on the local computer. |
Environment Variable Scopes
There are three scopes of environment variables. Think of scopes as layers of variables that build up to give a total picture. Combined, these “layers” provide many different environment variables to any running process in Windows.
Environment Variable Scope “Hierarchy”
Each of these “layers” either combine or overwrite one another. They are defined in a hierarchy like: machine –> user –> process with each scoped variable overwriting the parent variable if one exists in the parent scope.
For example, a common environment variable is TEMP
. This variable stores the folder path to Windows’ local temporary folder. This environment variable is set to:
C:\WINDOWS\TEMP
in the machine scopeC:\Users\<username>\AppData\Local\Temp
in the user scopeC:\Users\<username>\AppData\Local\Temp
in the process scope.
If there’s no TEMP
environment variable set in the user scope then the end result will be C:\WINDOWS\TEMP
.
Environment Variable Scope Types
There are three different environment variable scopes in Windows.
Machine
Environment variables in the machine scope are associated with the running instance of Windows. Any user account can read these, but setting, changing or deleting them needs to done with elevated privileges.
User
Environment variables in the user scope are associated with the user running the current process. User variables overwrite machine-scoped variables having the same name.
Note: Microsoft recommends that Machine and User scoped environment variable values contain no more than 2048 characters.
Process
Environment variables in the process scope are a combination of the machine and user scopes, along with some variables that Windows creates dynamically.
Below is a list of environment variables available to a running process. All of these variables are dynamically created.
ALLUSERSPROFILE
APPDATA
COMPUTERNAME
HOMEDRIVE
HOMEPATH
LOCALAPPDATA
LOGONSERVER
PROMPT
PUBLIC
SESSION
SystemDrive
SystemRoot
USERDNSDOMAIN
USERDOMAIN
USERDOMAIN_ROAMINGPROFILE
USERNAME
USERPROFILE
Environment Variables in the Registry
Environment variables are stored in two registry locations, one for the user scope and one for the machine scope.
Don’t Use the Registry to Manage Environment Variables
There’s a catch when making changes to variables inside of the registry. Any running processes will not see variable changes in the registry. Processes only see the registry variables and values that were present when the process was started, unless Windows notifies them that there has been a change.
Instead of modifying the registry directly, you can use a .NET class instead. The .NET [System.Environment]
class can modify machine and user–scoped environment variables and handle the registry housekeeping for you.
Modifying environment variables in the registry directly, whilst possible, doesn’t make sense. The .NET class offers a simpler, Microsoft-supported approach. You’ll learn about using the [System.Environment]
.NET class later in this article.
Environment Variable Registry Locations and Querying
I hope you’ve been convinced to not modify the registry directly but if you’d like to take a peek at what’s in there, you can find all user environment variables in the HKEY_CURRENT_USER\Environment
key. Machine-scoped environment variables are stored at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
.
Inside of either of these keys lies registry values of type REG_SZ
or REG_EXPAND_SZ
. REG_EXPAND_SZ
values hold environment variables embedded as part of their value. These environment variables are expanded when the value is retrieved.
To demonstrate this, use the REG
utility. This is a small command-line utility included with Windows.
Query the TEMP
environment variable as seen below. Run REG
with the QUERY
parameter to retrieve the value of the TEMP
variable.
> REG QUERY HKCU\Environment /V TEMP
HKEY_CURRENT_USER\Environment
TEMP REG_EXPAND_SZ %USERPROFILE%\AppData\Local\Temp
You’ll sometimes notice environment variables displayed surrounded by percentage symbols (
%COMPUTERNAME%
) like above. This is the old-school way of showing environment variables via cmd.exe and batch files. Know that PowerShell does not recognize this format.
The REG
utility allows us to see the native value of the registry value. The value type is REG_EXPAND_SZ
and the value contains the %USERPROFILE%
environment variable.
If you’d rather use PowerShell to retrieve the registry value, you can so using the Get-Item
cmdlet as shown below.
PS51> Get-ItemProperty -Path HKCU:\Environment -Name TEMP
TEMP : C:\Users\<your username>\AppData\Local\Temp
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Environment
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER
PSChildName : Environment
PSDrive : HKCU
PSProvider : Microsoft.PowerShell.Core\Registry
View and Set Windows Environment Variables via the GUI
To see a GUI view of the user and system environment variables, run SystemPropertiesAdvanced.exe from PowerShell, a command prompt or from Windows Key+R to display the System Properties Advanced tab. Click on the EnvironmentVariables button, which is highlighted in the image below.
The Environment Variables dialog, shown below, allows you to view, create and modify user and machine-scoped environment variables. Note that the dialog refers to machine scoped variables as System variables.
Now that you have an understanding of environment variables, let’s get to what you’re here for, managing them with PowerShell!
There are a few different ways you can interact with environment variables using PowerShell.
- The
Env:
PSDrive and Provider – session-based. Only sets the values of environment variables for the current PowerShell session $env:
variables – session-based. Only sets the values of environment variables for the current PowerShell session- The
[System.Environment]
.NET Class – allows you to persist user and system-scoped environment variables across sessions and reboots
The Env:
PSDrive and Provider
One of the best way to read environment variables is a PowerShell concept known as PowerShell drives (PS drives). A PS drive allows you to treat environment variables as if they are a file system through the Env:
drive.
Switching to the Env:
Drive
Like all PS drives, you reference it via paths like Env:\TEMP
, Env:\COMPUTERNAME
, etc. But to save some keystrokes, switch to the Env:
drive just as you would any file system drive, as shown below.
PS51> cd Env:
PS51 Env:\>
## or
PS51> Set-Location Env:
PS Env:\>
Tab-Completion with the Env:
Drive
You can use the same commands you would use to access a file system, such as Get-Item
and Get-ChildItem
to access environment variables. But instead of the file system, you’re reading the Env:
drive.
Because environment variables are stored in a PS drive, you can use the tab completion feature of PowerShell to cycle through the available variables, as shown below.
Let’s now jump into a couple of examples of how you can use the Env:
PS drive to work with environment variables.
Listing Environment Variables with Env:
PS51> Get-Item -Path Env:
PS51> Get-Item -Path Env:USERNAME
Listing Environment Variables Using a Wildcard with Env:
PS51> Get-Item -Path Env:user*
Finding Environment Variable Values with Env:
The results of these commands are key/value [System.Collections.DictionaryEntry]
.NET objects. These objects hold the environment variable’s name in the Name
property and the value in the Value
property.
You can access a specific value of an environment variable by wrapping the Get-Item
command reference in parentheses and referencing the Value
property as shown below:
PS51> (Get-Item -Path Env:computername).Value
MYCOMPUTERHOSTNAME
In situations where you need to only return certain environment variables, use standard PowerShell cmdlets such as Select-Object
and Where-Object
to select and filter the objects returned by the Env:
provider.
In the example below, only the environment variable COMPUTERNAME
is returned.
PS51> Get-ChildItem -Path Env: | Where-Object -Property Name -eq 'COMPUTERNAME'
As an alternative method, use the Get-Content
cmdlet. This cmdlet returns a [String]
object containing the value of the environment variable. This object is simpler to deal with as it returns only the value, rather than an object with Name
and Value
properties.
PS51> Get-Content -Path Env:\COMPUTERNAME
Demo: Inserting Environment Values in a String
Using Get-Content
, you can find the value of an environment variable and insert the COMPUTERNAME
environment variable, for example, into a text string.
PS51> 'Computer Name is: {0}' -f (Get-Content -Path Env:COMPUTERNAME)
Computer Name is: MYCOMPUTER
Setting an Environment Variable (And Creating) with Env:
Create new environment variables with PowerShell using the New-Item
cmdlet. Provide the name of the environment variable in the form Env:\<EnvVarName>
for the Name
value and the value of the environment variable for the Value
parameter as shown below.
PS51> New-Item -Path Env:\MYCOMPUTER -Value MY-WIN10-PC
Name Value
---- -----
MYCOMPUTER MY-WIN10-PC
Use the Set-item
cmdlet to set an environment variable, or create a new one if it doesn’t already exist. You can see below using the Set-Item
cmdlet, you can both create or modify and environment variable.
PS51> Set-Item -Path Env:testvariable -Value "Alpha"
Copying an Environment Variable with Env:
Sometimes the situation arises that you need to replicate the value of an environment variable. You can do this using the Copy-Item
cmdlet.
Below you can see that the value of the COMPUTERNAME
variable is copied to MYCOMPUTER
, overwriting its existing value.
PS51> Get-Item -Path Env:\MYCOMPUTER
Name Value
---- -----
MYCOMPUTER MY-WIN10-PC
PS51> Copy-Item -Path Env:\COMPUTERNAME -Destination Env:\MYCOMPUTER
PS51> Get-Item -Path Env:\MYCOMPUTER
Name Value
---- -----
MYCOMPUTER WIN10-1903
Removing an Environment Variable with Env:
Situations will arise where an environment variable is no longer needed. You can remove environment variables using one of three methods:
- Use the
Set-Item
cmdlet to set an environment variable to an empty value
PS51> Set-Item -Path Env:\MYCOMPUTER -Value ''
- Use the
Remove-Item
cmdlet.
PS51> Remove-Item -Path Env:\MYCOMPUTER
- Use the
Clear-Item
cmdlet.
PS51> Clear-Item -Path Env:\MYCOMPUTER
Renaming an Environment Variable with Env:
In situations where the name of an environment variable needs to be changed, you have the option to rename, rather than delete and recreate with the Env:
provider.
Use the Rename-Item
cmdlet to change the name of an environment variable whilst keeping its value. Below you can see that you can see that the MYCOMPUTER
variable is renamed to OLDCOMPUTER
whilst retaining its value.
PS51> Rename-Item -Path Env:\MYCOMPUTER -NewName OLDCOMPUTER
PS51> Get-Item -Path OLDCOMPUTER
Name Value
---- -----
OLDCOMPUTER WIN10-1903
$Env:
Variables
Having mastered the Env:
drive to treat environment variables as files, this section shows you how to treat them as variables. Another way you can manage in-session environment variables is using the the PowerShell Expression Parser. This feature allows you to use the $Env:
scope to access environment variables.
Getting an Environment Variable with $Env:
Using the $Env
scope, you can reference environment variables directly without using a command like Get-Item
as shown below.
This method makes it easy to insert environment variables into strings like below:
PS51> "The Computer Name is {0}" -f $env:computername
The Computer Name is WIN10-1809
PS51> "The Computer Name is $env:computername"
The Computer Name is WIN10-1809
Setting or Creating an Environment Variable with $Env:
Setting an environment variable using this method is straightforward. This will also create a new environment variable if one does not already exist like below.
PS51> $env:testvariable = "Alpha"
Use the +=
syntax to add to an existing value, rather than overwriting it.
PS51> $env:testvariable = "Alpha"
PS51> $env:testvariable += ",Beta"
PS51> $env:testvariable
Alpha,Beta
Removing an Environment Variable with $Env:
To remove an environment variable using this method, simple set its value to an empty string.
PS51> $env:testvariable = ''
Using the [System.Environment]
.NET Class
The .NET class [System.Environment]
offers methods for getting and setting environment variables also. This is only method to access various environment scopes directly and set environment variables that survive across PowerShell sessions.
In all of the following examples, if no scope is provided, the process scope is assumed.
When using the [System.Environment]
, you’ll use a few different .NET static class methods. You don’t need to understand what a static method is. You only need to understand to use any of the techniques you’re about to learn, you’ll need to first reference the class ([System.Environment]
) followed by two colons (::
) then followed by the method.
Listing Environment Variables with [System.Environment]
If you’d like to see all environment variables in a particular scope, you’d use the GetEnvironmentVariables
method. This method returns all environment variables by the scope specified as the method argument (in parentheses).
PS51> [System.Environment]::GetEnvironmentVariables('User')
PS51> [System.Environment]::GetEnvironmentVariables('Machine')
PS51> [System.Environment]::GetEnvironmentVariables('Process')
# The same as Process
PS51> [System.Environment]::GetEnvironmentVariables()
Getting Single Environment Variables with [System.Environment]
If you need to find a specific environment variable you can do so two different ways.
GetEnvironmentVariables().<var name>
– not recommendedGetEnvironmentVariable('<var name>','<scope>')
GetEnvironmentVariables()
Using the GetEnvironmentVariables()
method, you use dot notation to reference the value. Enclose the [System.Environment]
class and static method reference in parentheses followed by a dot then the name of the environment variable like below:
PS51> ([System.Environment]::GetEnvironmentVariables()).APPDATA
Note that when referencing environment variables this way, you must ensure you match capitalization! In the example above, try to reference the
APPDATA
variable usingappdata
. Use theGetEnvironmentVariable()
instead.
GetEnvironmentVariable()
Rather than using the GetEnvironmentVariables()
method, instead use GetEnvironmentVariable()
to find single environment variables. It gets around the issue with capitalization and also allows you to specify the scope.
To use this method, specify the environment variable name and the scope you’d like to look for that variable in separated by comma.
PS51> [System.Environment]::GetEnvironmentVariable('ComputerName','User')
# Blank
PS51> [System.Environment]::GetEnvironmentVariable('ComputerName','Machine')
# Blank
PS51> [System.Environment]::GetEnvironmentVariable('ComputerName','Process') WIN10-1903
# The same as Process
PS51> [System.Environment]::GetEnvironmentVariable('ComputerName')
WIN10-1903
Setting an Environment Variable with [System.Environment]
Use the SetEnvironmentVariable()
method to set the value of an environment variable for the given scope, or create a new one if it does not already exist.
When setting variables in the process scope, you’ll find that the process scope is volatile while changes to the user and machine scopes are permanent.
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable','Alpha','User')
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable','Alpha','Process')
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable','Alpha','Machine')
# The same as Process
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable','Alpha')
Note: Calling the SetEnvironmentVariable method with a variable name or value of 32767 characters or more will cause an exception to be thrown.
Removing an Environment Variable with [System.Environment]
Use the SetEnvironmentVariable()
method to remove an environment variable for the given scope by setting its value to an empty string.
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable', '', 'User')
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable', '', 'Process')
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable', '', 'Machine')
# The same as process
PS51> [System.Environment]::SetEnvironmentVariable('TestVariable', '')
Useful PowerShell Environment Variables
Like many other Windows applications, PowerShell has some environment variables of it’s own. Two useful environment variables to know about are PSExecutionPolicyPreference
and PSModulePath
.
PSExecutionPolicyPreference
The PSExecutionPolicyPreference
environment variable stores the current PowerShell execution policy. It is created if a session-specific PowerShell execution policy is set by:
- Running the
Set-ExecutionPolicy
cmdlet with aScope
parameter ofProcess
- Running the
powershell.exe
executable to start a new session, using theExecutionPolicy
command line parameter to set a policy for the session.
PSModulePath
The PSModulePath
environment variable contains the path that PowerShell searches for modules if you do not specify a full path. It is formed much like the standard PATH
environment variable, with individual directory paths separated by a semicolon.
PS51> $env:PSModulePath
C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
Quick tip: Split each folder to get a string array to process each path individually using $env:PSModulePath.split(‘;’)
Summary
Environment variables are a useful method for getting information about a running system, or storing information across sessions and reboots. Whether you’re just reading the default Windows operating system environment variables and creating your own, you now can manage them using a variety of ways with PowerShell!
Further Reading
- about_Environment_Variables
- The .NET [System.Environment] Class on Microsoft docs
- Learn the PowerShell string format and expanding strings
What is an environment variable in Windows? 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 variable! Read More →
The environment variables in Windows can be printed using the Windows command-line prompt (CMD) or using the PowerShell.
Windows Command-Line Prompt (CMD)
List all Windows environment variables and their values:
C:\> set
“Echo” the contents of a particular environment variable:
C:\> echo %ENVIRONMENT_VARIABLE%
Windows PowerShell
Print all Windows environment variables (names and values):
PS C:\> gci env:* | sort-object name
Show the contents of a particular environment variable:
PS C:\> echo $env:ENVIRONMENT_VARIABLE
Cool Tip: Set environment variables in Windows! Read More →
Was it useful? Share this post with the world!
Тема этого урока – переменные окружения или переменные среды (environment variable). Они используются для настройки операционной системы и в работе некоторых приложений (приложения дописывают свои пути в системную переменную %PATH%).
Переменные среды бывают двух типов – системные и локальные.
Системные переменные содержат одинаковое для всех пользователей значение, например %SYSTEMROOT% или %SYSTEMDRIVE%.
- %SYSTEMROOT% – указывает в какой папке установлена Windows. Как правило это C:\Windows
- %SYSTEMDRIVE% – указывает на системный диск. В большинстве случаев это C:\
Локальные переменные такие как %userprofile% или %temp% возвращают, в зависимости от имени пользователя, различное значение которое указывает на местонахождение профиля пользователя и на папку временных файлов.
Для проверки введите в окне командной строки последовательно команды:
echo %SYSTEMROOT% echo %USERPROFILE% echo %USERNAME% set
В PowerShell переменные окружения вынесены на специальный диск Env: его поставщиком является провайдер Environment который предоставляет доступ к переменным среды Windows.
cd env: dir
В более привычном виде можно использовать команду Get-ChildItem
Как видите полученные результаты ничем не отличаются от переменных выводимых командой set из командной строки.
Для демонстрации возможности получения значений переменных средствами Powershell создайте небольшой скрипт
$computer = $env:computername
$user = $env:username
cd $env:windir
Write-Host «$user, welcome to $computer!»
Сохраняем, запускаем, смотрим результат.
Для отображения и изменения значения переменных окружения служит конструкция представленная ниже. У нее следующий синтаксис:
$env:{имя переменной}
К примеру, чтобы вывести значение переменной %TEMP% необходимо ввести следующую команду:
$env:temp
Стоит отметить что в x64 системах переменная COMMONPROGRAMFILES(x86) указывающая на расположение каталога “Common Files” в Program Files (x86) для x64 ОС (обычно %ProgramFiles(x86)%\Common Files) пишется как
${env:CommonProgramFiles(x86)}
Так же обстоят дела с переменной PROGRAMFILES(x86) которая содержит путь к папке Program Files (x86) в x64 системах, для приложений архитектуры x86.
${env:ProgramFiles(x86)}
Изменение переменных окружения
Для изменения значений переменных среды можно использовать стандартные для Powershell командлеты Item, такие как Set-Item, Remove-Item и Copy-Item. Единственным исключением является Invoke-Item.
Для примера, можно взять сценарий – вам нужно добавить к переменной среды Path фрагмент “;c:\temp”. Вы используя командлет Set-Item выполняете следующую команду:
Set-Item -path env:path -value ($env:path + «;c:\temp»)
Задачу можно слегка упростить потому что значения переменных можно изменять без применения командлета, используя следующий синтаксис:
$env:{имя_переменной} = «{новое_значение}»
Вот пример использования.
$env:path = $env:path + «;c:\temp»
$env:path += «;c:\temp»
Переменные подвержены переименованию вполне стандартными для Powershell методами
rename-item -path env:My_Var -newname My_NewVar
Их даже можно копировать
copy-item -path env:My_Var -destination env:Other_Var
Сохранение изменений переменных среды
Чтобы создать или изменить значение переменной среды во всех сеансах Windows PowerShell, необходимо добавить изменение в профиль PowerShell.
Например, чтобы добавить каталог “C:\Temp” в переменную среды Path, необходимо добавить в профиль PowerShell следующую команду.
$env:path = $env:path + «;c:\temp»
Чтобы добавить команду в существующий профиль, например в профиль CurrentUser и AllHosts, введите:
add-content -path $profile.CurrentUserAllHosts -value ‘$env:path = $env:path + «;c:\temp»’
Закрываем консоль, открываем заново, проверяем что значение переменной PATH изменилось.
Примечание: Профилей в Powershell всего четыре, подробное их описание не укладывается в тематику переменных окружения и поэтому будет приведено отдельным уроком.
Создание собственных переменных окружения
Есть несколько различных способов создания новых переменных среды с помощью PowerShell.
Предположим, вам необходимо создать переменную окружения TestVar которую видно только в пределах текущего сеанса Powershell. В этом случае вы можете создать новую переменную окружения с помощью кода:
$env:TestVar = «This is a test environment variable.»
Или вторым методом
new-item -path Env: -name TestVa -value «This is a test environment variable.»
После этого вы сможете использовать созданную переменную в своих скриптах в пределах текущего сеанса.
Удаление переменных окружения
Удаление ненужной переменной производится командой Remove-Item, вот так:
Или альтернативный метод очистки
clear-item -path env:TestVar
Для чего это нужно?
Самый последний и самый важный пункт моего повествования…
Практическое применение переменных окружения на мой взгляд возможно в следующих сценариях:
- Скрипт по сбору данных который использует переменные окружения %USERDOMAIN%, %USERNAME% и пр.
- Скрипты генерирующие отчеты. Например промежуточные результаты очень удобно собирать во временнй папке (переменная %TEMP%).
Похожие статьи
Информация об авторе
Recently, someone from a PowerShell community asked me about setting environment variables in PowerShell. PowerShell provides different cmdlets to do this. Let me share with you here how to set and get environment variables in PowerShell.
To set an environment variable in PowerShell, you can simply use the $env
variable followed by the variable name and assign it a value. For example, to set the variable “MyVariable” to “Hello, World!”, you would use the command $env:MyVariable = "Hello, World!"
. This method sets the variable temporarily, making it available only in the current PowerShell session.
Environment variables are dynamic values that affect the way processes and applications run on a computer. They can store information such as file paths, system configurations, and user preferences. In Windows, environment variables can be user-specific or system-wide.
Now, let me show you how to set environment variables in PowerShell.
PowerShell offers multiple ways to set environment variables. Let’s look at a few common approaches.
1. Using the $env Variable
The simplest way to set an environment variable in PowerShell is by using the $env
variable followed by the variable name. Here’s an example:
$env:MyVariable = "Hello, World!"
In this case, we set the value of the environment variable named “MyVariable” to “Hello, World!”. This method sets the variable temporarily, meaning it will only be available in the current PowerShell session.
You can see the script after I executed it.
Check out PowerShell Print Variable
2. Using the Set-Item Cmdlet
Another way to set an environment variable in PowerShell is by using the Set-Item
cmdlet. This cmdlet allows you to modify the value of an existing variable or create a new one. Here’s an example:
Set-Item -Path Env:\MyVariable -Value "Hello, PowerShell!"
In this case, we use the Set-Item
cmdlet to set the value of “MyVariable” to “Hello, PowerShell!”. The -Path
parameter specifies the location of the environment variable, and the -Value
parameter sets its value.
3. Set Persistent Environment Variables
If you want to set an environment variable that persists across PowerShell sessions and system restarts, you can use the [Environment]::SetEnvironmentVariable()
method. Here’s an example:
[Environment]::SetEnvironmentVariable("MyVariable", "Persistent Value", "User")
In this case, we set the value of “MyVariable” to “Persistent Value” for the current user. The third parameter specifies the scope of the variable, which can be “User” or “Machine”.
Check out Get Computer Name in PowerShell
PowerShell: set environment variable for session
Temporary environment variables are set for the duration of the PowerShell session. Once the session is closed, these variables are discarded.
To set a temporary environment variable, use the $env:
prefix followed by the variable name and the assignment operator (=
). Here’s an example:
$env:MyTempVar = "TemporaryValue"
This command sets an environment variable named MyTempVar
with the value TemporaryValue
.
PowerShell: set environment variable permanently
Permanent environment variables persist across PowerShell sessions and system reboots. To set a permanent environment variable, you need to use the [System.Environment]::SetEnvironmentVariable
method.
To set a user-specific environment variable, use the following command:
[System.Environment]::SetEnvironmentVariable("MyUserVar", "UserValue", "User")
This command sets an environment variable named MyUserVar
with the value UserValue
for the current user.
Check out Set Variables in PowerShell
PowerShell: set environment variable machine level
To set a system-wide environment variable, use the following command. Note that you need administrative privileges to set system-wide variables:
[System.Environment]::SetEnvironmentVariable("MySystemVar", "SystemValue", "Machine")
This command sets an environment variable named MySystemVar
with the value SystemValue
for the entire system.
Get Environment Variable in PowerShell
Now that we know how to set environment variables let’s explore how to retrieve their values in PowerShell.
1. Using the $env Variable
To get the value of an environment variable in PowerShell, you can simply use the $env
variable followed by the variable name. Here’s an example:
$value = $env:MyVariable
Write-Host $value
In this case, we retrieve the value of “MyVariable” and store it in the $value
variable. We then use Write-Host
to display the value.
I executed the above PowerShell script, and you can see the output in the screenshot below:
2. Using the Get-ChildItem Cmdlet
Another way to get environment variables in PowerShell is by using the Get-ChildItem
cmdlet with the Env:
drive. Here’s an example:
Get-ChildItem Env:
This command retrieves all the environment variables defined in the current session and displays their names and values.
3. Using [System.Environment]
For a .NET approach, you can use:
[System.Environment]::GetEnvironmentVariable("MY_VARIABLE", "User")
This retrieves the value of a specific environment variable for the current user. Replace “User” with “Machine” for system-wide variables.
Conclusion
In this tutorial, I explained how to set and get environment variables in PowerShell. We covered different methods, including using the $env
variable, the Set-Item
cmdlet, and the [Environment]::SetEnvironmentVariable()
method. We also discussed how to retrieve the values of environment variables in PowerShell using the $env
variable and the Get-ChildItem
cmdlet.
You may also like:
- Restart a Computer Using PowerShell
- How to Change Directory in PowerShell?
- Remove Environment Variables in PowerShell
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.