Add environment variable windows 10 powershell

I have found out that setting the PATH environment variable affects only the old command prompt. PowerShell seems to have different environment settings. How do I change the environment variables for

My suggestion is this one:

I have tested this to add C:oraclex64bin to environment variable Path permanently and this works fine.

$ENV:PATH

The first way is simply to do:

$ENV:PATH=”$ENV:PATH;c:pathtofolder”

But this change isn’t permanent. $env:path will default back to what it was before as soon as you close your PowerShell terminal and reopen it again. That’s because you have applied the change at the session level and not at the source level (which is the registry level). To view the global value of $env:path, do:

Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINESystemCurrentControlSetControlSession ManagerEnvironment’ -Name PATH

Or more specifically:

(Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINESystemCurrentControlSetControlSession ManagerEnvironment’ -Name PATH).path

Now to change this, first we capture the original path that needs to be modified:

$oldpath = (Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINESystemCurrentControlSetControlSession ManagerEnvironment’ -Name PATH).path

Now we define what the new path should look like. In this case we are appending a new folder:

$newpath = “$oldpath;c:pathtofolder”

Note: Be sure that the $newpath looks how you want it to look. If not, then you could damage your OS.

Now apply the new value:

Set-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINESystemCurrentControlSetControlSession ManagerEnvironment’ -Name PATH -Value $newPath

Now do one final check that it looks like how you expect it to:

(Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINESystemCurrentControlSetControlSession ManagerEnvironment’ -Name PATH).Path

You can now restart your PowerShell terminal (or even reboot the machine) and see that it doesn’t rollback to its old value again.

Note the ordering of the paths may change so that it’s in alphabetical order, so make sure you check the whole line. To make it easier, you can split the output into rows by using the semi-colon as a delimiter:

($env:path).split(“;”)

При работе с переменными окружения в Powershell есть ряд проблем, с которыми мы можем столкнуться. Если мы выполним следующую команду, то увидим, что у нас есть диск и именем Env, который и хранит переменные:

Get-PSDrive -PSProvider "Environment"

Powershell provider

Мы можем в него перейти и увидеть все переменные окружения:

cd ENV:
ls

Если мы попробуем изменить переменные следующим способом, то они будут работать только в рамках PS и до окончания сеанса (перезагрузки например):

$variable = (Get-Item -Path 'Env:Path').Value
$new_path = $variable + ';C:Git'
Set-Item -Path Env:Path -Value $new_path

Способ выше аналогичен этому:

$Env:Path += ";C:Git"

Если нам нужно сделать переменную среды постоянной есть решение для компьютера и конкретного пользователя.

Изменение переменных окружения пользователя в Powershell

У нас есть ветка реестра, которая отвечает за область пользователя:

HKEY_CURRENT_USEREnvironmentPath

В деталях мы уже рассматривали как работать в powershell с реестром и не будем разбирать в деталях. Способом ниже мы обратимся к Path и добавим значение «C:Git»:

$variable = Get-ItemPropertyValue -Path 'HKCU:Environment' -Name 'Path'
$new_path = $variable + ';C:Git'
Set-ItemProperty -Path 'HKCU:Environment' -Name 'Path' -Value $new_path

Обращайте внимание, что у вас стоит ; перед новым значением (если вы изменяете Path), и что вы сохраняете предыдущее значение путем сложения.

Изменение переменных пользователя Powershell

Изменение переменных Env компьютера в Powershell

У нас есть другая ветка реестра, которая хранит значения переменных компьютера:

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment

Изменяются они так же, как и в случае с пользователем:

$reg = 'HKLM:SYSTEMCurrentControlSetControlSession ManagerEnvironment'
$variable = Get-ItemPropertyValue -Path $reg -Name 'Path'
$new_path = $variable + ';C:Git'
Set-ItemProperty -Path $reg -Name 'Path' -Value $new_path

Создание новых переменных Environment в Powershell

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

Для компьютера:

$var = 'siteName'
$znachenie = 'fixmypc.ru'
[System.Environment]::SetEnvironmentVariable($var,$znachenie,[System.EnvironmentVariableTarget]::Machine)

И для пользователя:

[System.Environment]::SetEnvironmentVariable($var,$znachenie,[System.EnvironmentVariableTarget]::User)

Powershell добавить переменную окружения Env

Теги:

#powershell

Смотрите также «Полный список переменных окружения Windows».

В PowerShell вы можете получать, добавлять, изменять, очищать и удалять значения переменных окружения.

Переменные среды — это переменные, которые описывают среду, в которой работают ваши программы. Windows и PowerShell используют переменные среды для хранения постоянной информации, которая влияет на выполнение системы и процессов. В отличие от переменных PowerShell, переменные среды не подлежат ограничениям области видимости.

Environment представляет собой плоское пространство имён, содержащее переменные среды, характерные для текущего сеанса пользователя. Переменные среды не имеют дочерних элементов.

Чтобы показать все переменные окружения в PowerShell используйте команду:

Get-ChildItem Env:

Точно такой же результат будет получен при использовании сокращённой записи этой команды:

gci env:

Командлет Get-Item даст точно такой же результат — выведет все переменные окружения:

Get-Item Env:

Для постраничного вывода информации с возможностью пролистывания используйте следующую команду:

Get-ChildItem Env: | more

Для сохранения вывода в файл output.txt, который можно открыть в любом редакторе, например в Notepad.:

Get-ChildItem Env: > output.txt

Чтобы показать значения всех переменных в списке, отсортированным по именам переменных:

Get-ChildItem Env: | Sort Name

Как показать значение переменной окружения в PowerShell

Чтобы показать значение только одной переменной, используйте конструкцию:

gci env: | where name -contain 'ИМЯ-ПЕРЕМЕННОЙ'

К примеру, чтобы показать значение только PROCESSOR_ARCHITECTURE:

gci env: | where name -contain 'PROCESSOR_ARCHITECTURE'

Чтобы показать значение всех переменных, соответствующих указанному шаблону, используйте команду вида:

gci env: | where name -like 'ЧАСТЬ-ИМЕНИ*'

Например, чтобы показать значения всех переменных, чьё имя начинается на «Pro»:

gci env: | where name -like 'Pro*'

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

Следующая команда выведет содержимое WINDIR:

Get-ChildItem -Path Env:windir

Эта команда также покажет значение переменной окружения WINDIR (обратите внимание на разницу в форматировании):

$env:windir

Как установить или поменять значение переменной окружения в PowerShell

Для установки новой переменной окружения используется команда вида:

$Env:<ИМЯ-ПЕРЕМЕННОЙ> = "<НОВОЕ-ЗНАЧЕНИЕ>"

Например:

Например, чтобы установить значение переменной servpath на c:/Server:

$Env:servpath = "c:/Server"

Чтобы добавить;c:temp к значению переменной окружения Path используйте следующий синтаксис:

$Env:Path += ";c:temp"

На Linux или MacOS в качестве разделителя используйте двоеточие (:), чтобы отделить новый путь от имеющихся путей.

$Env:PATH += ":/usr/local/temp"

Вы также можете использовать командлеты PowerShell, такие как Set-Item, Remove-Item и Copy-Item для изменения значений переменных окружения.

Пример использования командлета Set-Item для добавления ;c:temp к значению переменной окружения Path

Set-Item -Path Env:Path -Value ($Env:Path + ";C:Temp")

В этой команде значение заключено в кавычки, чтобы оно интерпретировалось как единый юнит.

Как удалить переменную окружения в PowerShell

Эта команда удаляет переменную окружения USERROLE2 из текущей сессии:

Remove-Item -Path Env:USERROLE2

Эта команда удаляет переменную окружения USERROLE очищая её значение:

Clear-Item -Path Env:USERROLE

Связанные статьи:

  • Как в командной строке Windows вывести все переменные среды (100%)
  • Основы запуска и использования утилит командной строки в Windows (100%)
  • Переменные окружения Windows (93.3%)
  • Работа с переменными окружения в командной строке (CMD) (93.3%)
  • Как включить удалённый рабочий стол RDP в Windows Server 2019 (62.6%)
  • Windows 10: нет подключения к Интернету после подключения к VPN-серверу (РЕШЕНО) (RANDOM — 56.7%)
  1. What Are Environment Variables
  2. Set an Environment Variable With Env: in PowerShell
  3. Set the [System.Environment] .NET Class in PowerShell
  4. Refresh Environment Variables on Current PowerShell Session

Set Environment Variables Using PowerShell

Using Windows PowerShell to set Windows environment variables, read environment variables and create new environment variables is easy once we know the proper execution of commands.

PowerShell provides many different methods to interact with Windows environment variables from the $env: PSDrive and the [System.Environment] .NET class. This article will discuss setting environment variables and refreshing them in our current session using PowerShell.

What Are Environment Variables

As the name suggests, environment variables store information about Windows and applications’ environments.

We can access environment variables through a graphical interface such as Windows Explorer and plain text editors like Notepad, cmd.exe, and PowerShell.

Using environment variables helps us avoid hard-coding file paths, user or computer names, and more in our PowerShell scripts or modules.

Set an Environment Variable With Env: in PowerShell

We can create new environment variables with PowerShell using the New-Item cmdlet. But, first, provide the environment variable’s name in the Env:<EnvVarName> format for the Value parameter, as shown below.

Example Code:

New-Item -Path Env:TEST -Value WIN10-DESKTOP

Output:

Name                           Value
----                           -----
TEST                           WIN10-DESKTOP

We can use the Set-Item cmdlet to set an environment variable or create a new one if it doesn’t already exist. For example, we can see below using the Set-Item cmdlet.

We can both make or modify an environment variable.

Example Code:

Set-Item -Path Env:TEST -Value "TestValue"

Set the [System.Environment] .NET Class in PowerShell

The [System.Environment] will use a few different .NET static class methods. We don’t need to understand what a static way is.

We only need to understand to use any of the techniques we are about to learn, and we will need first to reference the class ([System.Environment]) followed by two colons (::) then followed by the method.

To set the environment variable using the .NET class stated, use the SetEnvironmentVariable() function to set the value of an existing environment variable for the given scope or create a new environment variable if it does not already exist.

When setting variables in the process scope, we will find that the process scope is volatile and existing in the current session while changes to the user and machine scopes are permanent.

Example Code:

[System.Environment]::SetEnvironmentVariable('TestVariable','TestValue','User')

Refresh Environment Variables on Current PowerShell Session

To use our new set of environment variables in our PowerShell session, get the environment variable of the user profile and machine through the .NET class and assign it to the PowerShell environment variable.

Since environment variables are also considered PowerShell variables, we can assign values to them directly more straightforwardly.

Example Code:

$env:PATH = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")

To set the environmental variable using PowerShell you need to use the assignment operator (=). If the
variable already exists then you can use the += operator to append the value, otherwise, a new environment variable will be created.

For example, there is no AZURE_RESOURCE_GROUP environment variable that exists in the system. We can create it as below.

$env:AZURE_RESOURCE_GROUP = 'MyTestResourceGroup'

Now when you check the environment variables in the system, you will get the above variable name.

PS C:Windowssystem32> dir env:
Name                            Value
----                            -----
ALLUSERSPROFILE                 C:ProgramData
APPDATA                         C:UsersdeltaAppDataRoaming
AZURE_RESOURCE_GROUP            MyTestResourceGroup
CommonProgramFiles              C:Program FilesCommon Files
CommonProgramFiles(x86)         C:Program Files (x86)Common Files
CommonProgramW6432              C:Program FilesCommon Files
COMPUTERNAME                    TEST1-WIN2K12
ComSpec                         C:Windowssystem32cmd.exe

If you have another resource group and if you need to add to the same environment variable then as
mentioned earlier use += operator and separate value with a semicolon (;).

$env:AZURE_RESOURCE_GROUP = ';MyTestResourceGroup2'
PS C:Windowssystem32> $env:AZURE_RESOURCE_GROUP
MyTestResourceGroup;MyTestResourceGroup2

If the value(s) already exists for an environment variable then you can also change the value by simply assigning the value to the variable. For example,

PS C:Windowssystem32> $env:AZURE_RESOURCE_GROUP = 'NewResourceGroup'
PS C:Windowssystem32> $env:AZURE_RESOURCE_GROUP
NewResourceGroup

The above method we have seen is to set the environment variable temporarily, once you close the
PowerShell console the value gets destroyed. To add or set the environment variable persistently you
need to use the .NET method.

Setting Environment Variable Persistently

To set the environment persistently so they should remain even when close the session, PowerShell uses [System.Environment] class with the SetEnvironmentVariable method for the environment variable to set it persistently.

[System.Environment]::SetEnvironmentVariable('ResourceGroup','AZ_Resource_Group')
PS C:> $env:ResourceGroup
AZ_Resource_Group

Понравилась статья? Поделить с друзьями:
  • Add an exclusion to windows security
  • Add an exception to the windows firewall
  • Add an exception for utorrent in windows firewall что это
  • Add an exception for utorrent in windows firewall что значит
  • Add an exception for torrent in windows firewall что это