- New-Variable
- Syntax
- Description
- Examples
- Example 1: Create a variable
- Example 2: Create a variable and assign it a value
- Example 3: Create a variable with the ReadOnly option
- Example 4: Assign multiple options to a variable
- Example 5: Create a private variable
- Example 6: Create a variable with a space
- Parameters
- Сведения о переменных среды About Environment Variables
- КРАТКОЕ ОПИСАНИЕ SHORT DESCRIPTION
- ПОДРОБНОЕ ОПИСАНИЕ LONG DESCRIPTION
- Использование и изменение переменных среды Using and changing environment variables
- Переменные среды, в которых хранятся настройки Environment variables that store preferences
- Управление переменными среды Managing environment variables
- Использование поставщика среды Using the Environment provider
- Использование командлетов Item Using Item cmdlets
- Сохранение изменений в переменных среды Saving changes to environment variables
- Использование методов System. Environment Using System.Environment methods
New-Variable
Creates a new variable.
Syntax
Description
The New-Variable cmdlet creates a new variable in Windows PowerShell. You can assign a value to the variable while creating it or assign or change the value after it is created.
You can use the parameters of New-Variable to set the properties of the variable, set the scope of a variable, and determine whether variables are public or private.
Typically, you create a new variable by typing the variable name and its value, such as $Var = 3 , but you can use the New-Variable cmdlet to use its parameters.
Examples
Example 1: Create a variable
This command creates a new variable named days. You are not required to type the Name parameter.
Example 2: Create a variable and assign it a value
This command creates a variable named zipcode and assigns it the value 98033.
Example 3: Create a variable with the ReadOnly option
This example shows how to use the ReadOnly option of New-Variable to protect a variable from being overwritten.
The first command creates a new variable named Max and sets its value to 256. It uses the Option parameter with a value of ReadOnly .
The second command tries to create a second variable with the same name. This command returns an error, because the read-only option is set on the variable.
The third command uses the Force parameter to override the read-only protection on the variable. In this case, the command to create a new variable with the same name succeeds.
Example 4: Assign multiple options to a variable
This example creates a variable and assigns the AllScope and Constant options so the variable will be available in the current scope and any new scopes created and cannot be changed or deleted.
Example 5: Create a private variable
This command demonstrates the behavior of a private variable in a module. The module contains the Get-Counter cmdlet, which has a private variable named Counter. The command uses the Visibility parameter with a value of Private to create the variable.
The sample output shows the behavior of a private variable. The user who has loaded the module cannot view or change the value of the Counter variable, but the Counter variable can be read and changed by the commands in the module.
Example 6: Create a variable with a space
This command demonstrates that variables with spaces can be created. The variables can be accessed using the Get-Variable cmdlet or directly by delimiting a variable with braces.
Parameters
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a description of the variable.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates that the cmdlet creates a variable with the same name as an existing read-only variable.
By default, you can overwrite a variable unless the variable has an option value of ReadOnly or Constant . For more information, see the Option parameter.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a name for the new variable.
Type: | String |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the value of the Options property of the variable. The acceptable values for this parameter are:
- None — Sets no options. None is the default.
- ReadOnly — Can be deleted. Cannot be changed, except by using the Force parameter.
- Private — The variable is available only in the current scope.
- AllScope — The variable is copied to any new scopes that are created.
- Constant — Cannot be deleted or changed. Constant is valid only when you are creating a variable. You cannot change the options of an existing variable to Constant .
These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the Option parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values.
To see the Options property of all variables in the session, type Get-Variable | Format-Table -Property name, options -AutoSize .
Type: | ScopedItemOptions |
Accepted values: | None, ReadOnly, Constant, Private, AllScope, Unspecified |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the scope of the new variable. The acceptable values for this parameter are:
- Global — Variables created in the global scope are accessible everywhere in a PowerShell process.
- Local — The local scope refers to the current scope, this can be any scope depending on the context.
- Script — Variables created in the script scope are accessible only within the script file or module they are created in.
- Private — Variables created in the private scope cannot be accessed outside the scope they exist in. You can use private scope to create a private version of an item with the same name in another scope.
- A number relative to the current scope (0 through the number of scopes, where 0 is the current scope, 1 is its parent, 2 the parent of the parent scope, and so on). Negative numbers cannot be used.
Local is the default scope when the scope parameter is not specified.
For more information, see about_Scopes.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the initial value of the variable.
Type: | Object |
Position: | 1 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Determines whether the variable is visible outside of the session in which it was created. This parameter is designed for use in scripts and commands that will be delivered to other users. The acceptable values for this parameter are:
- Public — The variable is visible. Public is the default.
- Private — The variable is not visible.
When a variable is private, it does not appear in lists of variables, such as those returned by Get-Variable , or in displays of the Variable: drive. Commands to read or change the value of a private variable return an error. However, the user can run commands that use a private variable if the commands were written in the session in which the variable was defined.
Type: | SessionStateEntryVisibility |
Accepted values: | Public, Private |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Сведения о переменных среды About Environment Variables
КРАТКОЕ ОПИСАНИЕ SHORT DESCRIPTION
Описывает, как получить доступ к переменным среды Windows в PowerShell. Describes how to access Windows environment variables in PowerShell.
ПОДРОБНОЕ ОПИСАНИЕ LONG DESCRIPTION
Переменные среды хранят сведения о среде операционной системы. Environment variables store information about the operating system environment. Эти сведения включают в себя такие сведения, как путь операционной системы, количество процессоров, используемых операционной системой, и расположение временных папок. This information includes details such as the operating system path, the number of processors used by the operating system, and the location of temporary folders.
Переменные среды хранят данные, используемые операционной системой и другими программами. The environment variables store data that is used by the operating system and other programs. Например, WINDIR переменная среды содержит расположение каталога установки Windows. For example, the WINDIR environment variable contains the location of the Windows installation directory. Программы могут запрашивать значение этой переменной, чтобы определить, где находятся файлы операционной системы Windows. Programs can query the value of this variable to determine where Windows operating system files are located.
PowerShell может обращаться к переменным среды и управлять ими на любой из поддерживаемых платформ операционной системы. PowerShell can access and manage environment variables in any of the supported operating system platforms. Поставщик среды PowerShell упрощает этот процесс, облегчая просмотр и изменение переменных среды. The PowerShell environment provider simplifies this process by making it easy to view and change environment variables.
Переменные среды, в отличие от других типов переменных в PowerShell, наследуются дочерними процессами, такими как локальные фоновые задания и сеансы, в которых выполняются элементы модуля. Environment variables, unlike other types of variables in PowerShell, are inherited by child processes, such as local background jobs and the sessions in which module members run. Это делает переменные среды наиболее подходящими для хранения значений, необходимых как в родительских, так и в дочерних процессах. This makes environment variables well suited to storing values that are needed in both parent and child processes.
Использование и изменение переменных среды Using and changing environment variables
В Windows переменные среды могут быть определены в трех областях: On Windows, environment variables can be defined in three scopes:
- Область компьютера (или системы) Machine (or System) scope
- Область пользователей User scope
- Область процесса Process scope
Область процесса содержит переменные среды, доступные в текущем процессе, или сеанс PowerShell. The Process scope contains the environment variables available in the current process, or PowerShell session. Этот список переменных наследуется от родительского процесса и создается из переменных в областях компьютера и пользователя . This list of variables is inherited from the parent process and is constructed from the variables in the Machine and User scopes. Платформы на базе UNIX имеют только область процесса . Unix-based platforms only have the Process scope.
Можно отображать и изменять значения переменных среды без использования командлета с помощью переменных синтаксиса в поставщике среды. You can display and change the values of environment variables without using a cmdlet by using a variable syntax with the environment provider. Чтобы отобразить значение переменной среды, используйте следующий синтаксис: To display the value of an environment variable, use the following syntax:
Например, чтобы отобразить значение WINDIR переменной среды, введите в командной строке PowerShell следующую команду: For example, to display the value of the WINDIR environment variable, type the following command at the PowerShell command prompt:
В этом синтаксисе знак доллара ( $ ) указывает на переменную, а имя диска ( Env: ) указывает на переменную среды, за которой следует имя переменной ( windir ). In this syntax, the dollar sign ( $ ) indicates a variable, and the drive name ( Env: ) indicates an environment variable followed by the variable name ( windir ).
Изменение переменных среды в PowerShell влияет только на текущий сеанс. When you change environment variables in PowerShell, the change affects only the current session. Это поведение напоминает поведение Set команды в командной оболочке Windows и Setenv команду в средах на базе UNIX. This behavior resembles the behavior of the Set command in the Windows Command Shell and the Setenv command in UNIX-based environments. Чтобы изменить значения в областях компьютера или пользователя, необходимо использовать методы класса System. Environment . To change values in the Machine or User scopes, you must use the methods of the System.Environment class.
Чтобы внести изменения в переменные на уровне компьютера, необходимо также иметь разрешение. To make changes to Machine-scoped variables, must also have permission. Если вы попытаетесь изменить значение без достаточных разрешений, команда завершится ошибкой, и в PowerShell отобразится сообщение об ошибке. If you try to change a value without sufficient permission, the command fails and PowerShell displays an error.
Можно изменить значения переменных без использования командлета, используя следующий синтаксис: You can change the values of variables without using a cmdlet using the following syntax:
Например, чтобы добавить ;c:\temp к значению Path переменной среды, используйте следующий синтаксис: For example, to append ;c:\temp to the value of the Path environment variable, use the following syntax:
В Linux или macOS двоеточие ( : ) в команде отделяет новый путь от пути, расположенного перед ним в списке. On Linux or macOS, the colon ( : ) in the command separates the new path from the path that precedes it in the list.
Можно также использовать командлеты Item, такие как Set-Item , Remove-Item и, Copy-Item чтобы изменить значения переменных среды. You can also use the Item cmdlets, such as Set-Item , Remove-Item , and Copy-Item to change the values of environment variables. Например, чтобы использовать Set-Item командлет для добавления ;c:\temp к значению Path переменной среды, используйте следующий синтаксис: For example, to use the Set-Item cmdlet to append ;c:\temp to the value of the Path environment variable, use the following syntax:
В этой команде значение заключается в круглые скобки, чтобы интерпретироваться как единое целое. In this command, the value is enclosed in parentheses so that it is interpreted as a unit.
Переменные среды, в которых хранятся настройки Environment variables that store preferences
Функции PowerShell могут использовать переменные среды для хранения настроек пользователя. PowerShell features can use environment variables to store user preferences. Эти переменные работают подобно переменным предпочтений, но они наследуются дочерними сеансами сеансов, в которых они созданы. These variables work like preference variables, but they are inherited by child sessions of the sessions in which they are created. Дополнительные сведения о переменных предпочтений см. в разделе about_preference_variables. For more information about preference variables, see about_preference_variables.
Ниже перечислены переменные среды, в которых хранятся настройки. The environment variables that store preferences include:
Хранит политику выполнения, заданную для текущего сеанса. Stores the execution policy set for the current session. Эта переменная среды существует только в том случае, если задана политика выполнения для одного сеанса. This environment variable exists only when you set an execution policy for a single session. Это можно сделать двумя разными способами. You can do this in two different ways.
Запустите сеанс из командной строки с помощью параметра ExecutionPolicy , чтобы задать политику выполнения для сеанса. Start a session from the command line using the ExecutionPolicy parameter to set the execution policy for the session.
Используйте командлет Set-ExecutionPolicy . Use the Set-ExecutionPolicy cmdlet. Используйте параметр Scope со значением «Process». Use the Scope parameter with a value of «Process».
PowerShell обеспечивает контроль над файлом, используемым для кэширования данных о модулях и их командлетах. PowerShell provides control over the file that is used to cache data about modules and their cmdlets. Кэш считывается при запуске во время поиска команды и записывается в фоновом потоке после импорта модуля. The cache is read at startup while searching for a command and is written on a background thread sometime after a module is imported.
Расположение кэша по умолчанию: Default location of the cache is:
- Windows PowerShell 5.1: $env:LOCALAPPDATA\Microsoft\Windows\PowerShell . Windows PowerShell 5.1: $env:LOCALAPPDATA\Microsoft\Windows\PowerShell
- PowerShell 6,0 и более поздние версии: $env:LOCALAPPDATA\Microsoft\PowerShell PowerShell 6.0 and higher: $env:LOCALAPPDATA\Microsoft\PowerShell
- По умолчанию не для Windows:
/.cache/powershell Non-Windows default:
По умолчанию для кэша используется имя файла ModuleAnalysisCache . The default filename for the cache is ModuleAnalysisCache . Если установлено несколько экземпляров PowerShell, имя файла включает в себя шестнадцатеричный суффикс, чтобы для каждой установки существовало уникальное имя файла. When you have multiple instances of PowerShell installed, the filename includes a hexadecimal suffix so that there is a a unique filename per installation.
Если обнаружение команд работает неправильно, например, в IntelliSense отображаются несуществующие команды, можно удалить файл кэша. If command discovery isn’t working correctly, for example Intellisense shows commands that don’t exist, you can delete the cache file. Кэш создается повторно при следующем запуске PowerShell. The cache is recreated the next time you start PowerShell.
Чтобы изменить расположение кэша по умолчанию, задайте переменную среды перед запуском PowerShell. To change the default location of the cache, set the environment variable before starting PowerShell. Изменения этой переменной среды влияют только на дочерние процессы. Changes to this environment variable only affect child processes. Значение должно быть полным путем (включая имя файла), на создание и запись файлов по которому у среды PowerShell есть разрешение. The value should name a full path (including filename) that PowerShell has permission to create and write files.
Чтобы отключить файловый кэш, укажите в качестве этого значения недопустимое расположение, например: To disable the file cache, set this value to an invalid location, for example:
Это задает путь к устройству NUL . This sets the path to the NUL device. PowerShell не удается выполнить запись в путь, но ошибка не возвращается. PowerShell can’t write to the path but no error is returned. Вы можете увидеть ошибки, о которых сообщили с помощью трассировки: You can see the errors reported using a tracer:
При вызаписи кэша анализа модуля PowerShell проверяет наличие модулей, которые больше не существуют, чтобы избежать необязательного большого объема кэша. When writing out the module analysis cache, PowerShell checks for modules that no longer exist to avoid an unnecessarily large cache. Иногда эти проверки нежелательны. в этом случае их можно отключить, задав для этого значения переменной среды значение 1 . Sometimes these checks are not desirable, in which case you can turn them off by setting this environment variable value to 1 .
Установка этой переменной среды вступает в силу немедленно в текущем процессе. Setting this environment variable takes effect immediately in the current process.
$env:PSModulePath Переменная среды содержит список расположений папок, в которых выполняется поиск модулей и ресурсов. The $env:PSModulePath environment variable contains a list of folder locations that are searched to find modules and resources.
По умолчанию действующие расположения, назначенные, $env:PSModulePath являются: By default, the effective locations assigned to $env:PSModulePath are:
Расположения на уровне системы. Эти папки содержат модули, поставляемые с PowerShell. System-wide locations: These folders contain modules that ship with PowerShell. Модули хранятся в $PSHOME\Modules расположении. The modules are store in the $PSHOME\Modules location. Кроме того, это расположение, в котором устанавливаются модули управления Windows. Also, This is the location where the Windows management modules are installed.
Модули, установленные пользователем: это модули, установленные пользователем. User-installed modules: These are modules installed by the user. Install-Module имеет параметр области , который позволяет указать, установлен ли модуль для текущего пользователя или для всех пользователей. Install-Module has a Scope parameter that allows you to specify whether the module is installed for the current user or for all users. Дополнительные сведения см. в разделе Install-Module. For more information, see Install-Module.
- В Windows расположением определяемой пользователем области CurrentUser является $HOME\Documents\PowerShell\Modules Папка. On Windows, the location of the user-specific CurrentUser scope is the $HOME\Documents\PowerShell\Modules folder. Областью ALLUSERS является расположение $env:ProgramFiles\PowerShell\Modules . The location of the AllUsers scope is $env:ProgramFiles\PowerShell\Modules .
- В системах, отличных от Windows, расположением определяемой пользователем области CurrentUser является $HOME/.local/share/powershell/Modules Папка. On non-Windows systems, the location of the user-specific CurrentUser scope is the $HOME/.local/share/powershell/Modules folder. Областью ALLUSERS является расположение /usr/local/share/powershell/Modules . The location of the AllUsers scope is /usr/local/share/powershell/Modules .
Кроме того, программы установки, устанавливающие модули в других каталогах, например каталог Program Files, могут добавлять свои расположения к значению $env:PSModulePath . In addition, setup programs that install modules in other directories, such as the Program Files directory, can append their locations to the value of $env:PSModulePath .
Дополнительные сведения см. в разделе about_PSModulePath. For more information, see about_PSModulePath.
Управление переменными среды Managing environment variables
PowerShell предоставляет несколько различных методов для управления переменными среды. PowerShell provides several different methods for managing environment variables.
- Диск поставщика среды The Environment provider drive
- Командлеты элементов The Item cmdlets
- Класс .NET System. Environment The .NET System.Environment class
- В Windows Панель управления системы On Windows, the System Control Panel
Использование поставщика среды Using the Environment provider
Каждая переменная среды представлена экземпляром класса System. Collections. DictionaryEntry . Each environment variable is represented by an instance of the System.Collections.DictionaryEntry class. В каждом объекте DictionaryEntry имя переменной среды является ключом словаря. In each DictionaryEntry object, the name of the environment variable is the dictionary key. Значением переменной является значение словаря. The value of the variable is the dictionary value.
Чтобы отобразить свойства и методы объекта, представляющего переменную среды в PowerShell, используйте Get-Member командлет. To display the properties and methods of the object that represents an environment variable in PowerShell, use the Get-Member cmdlet. Например, чтобы отобразить методы и свойства всех объектов на Env: диске, введите: For example, to display the methods and properties of all the objects in the Env: drive, type:
Поставщик среды PowerShell позволяет получить доступ к переменным среды на диске PowerShell ( Env: диск). The PowerShell Environment provider lets you access environment variables in a PowerShell drive (the Env: drive). Этот диск выглядит примерно так же, как диск файловой системы. This drive looks much like a file system drive. Чтобы открыть Env: диск, введите: To go to the Env: drive, type:
Используйте командлеты Content, чтобы получить или задать значения переменной среды. Use the Content cmdlets to get or set the values of an environment variable.
Можно просмотреть переменные среды на Env: диске с любого другого диска PowerShell, а также можно перейти на Env: диск, чтобы просмотреть и изменить переменные среды. You can view the environment variables in the Env: drive from any other PowerShell drive, and you can go into the Env: drive to view and change the environment variables.
Использование командлетов Item Using Item cmdlets
При ссылке на переменную среды введите Env: имя диска, за которым следует имя переменной. When you refer to an environment variable, type the Env: drive name followed by the name of the variable. Например, чтобы отобразить значение COMPUTERNAME переменной среды, введите: For example, to display the value of the COMPUTERNAME environment variable, type:
Чтобы отобразить значения всех переменных среды, введите: To display the values of all the environment variables, type:
Так как переменные среды не имеют дочерних элементов, выходные данные Get-Item и Get-ChildItem одинаковы. Because environment variables do not have child items, the output of Get-Item and Get-ChildItem is the same.
По умолчанию PowerShell отображает переменные среды в том порядке, в котором они извлекаются. By default, PowerShell displays the environment variables in the order in which it retrieves them. Чтобы отсортировать список переменных среды по имени переменной, необходимо передать выходные данные Get-ChildItem команды в Sort-Object командлет. To sort the list of environment variables by variable name, pipe the output of a Get-ChildItem command to the Sort-Object cmdlet. Например, с любого диска PowerShell введите: For example, from any PowerShell drive, type:
Вы также можете войти на Env: диск с помощью Set-Location командлета: You can also go into the Env: drive by using the Set-Location cmdlet:
Если вы используете Env: диск, можно опустить Env: имя диска из пути. When you are in the Env: drive, you can omit the Env: drive name from the path. Например, чтобы отобразить все переменные среды, введите: For example, to display all the environment variables, type:
Чтобы отобразить значение COMPUTERNAME переменной в пределах Env: диска, введите: To display the value of the COMPUTERNAME variable from within the Env: drive, type:
Сохранение изменений в переменных среды Saving changes to environment variables
Чтобы внести постоянное изменение в переменную среды в Windows, используйте панель управления «система». To make a persistent change to an environment variable on Windows, use the System Control Panel. Выберите Дополнительные параметры системы. Select Advanced System Settings. На вкладке Дополнительно щелкните переменная среды. . Можно добавлять или изменять существующие переменные среды в области пользователя и системы (компьютера). On the Advanced tab, click Environment Variable. . You can add or edit existing environment variables in the User and System (Machine) scopes. Windows записывает эти значения в реестр, чтобы они сохранялись в сеансах и перезапусках системы. Windows writes these values to the Registry so that they persist across sessions and system restarts.
Кроме того, можно добавить или изменить переменные среды в профиле PowerShell. Alternately, you can add or change environment variables in your PowerShell profile. Этот метод работает для любой версии PowerShell на любой поддерживаемой платформе. This method works for any version of PowerShell on any supported platform.
Использование методов System. Environment Using System.Environment methods
Класс System. Environment предоставляет методы GetEnvironmentVariable и SetEnvironmentVariable , позволяющие указать область действия переменной. The System.Environment class provides GetEnvironmentVariable and SetEnvironmentVariable methods that allow you to specify the scope of the variable.
В следующем примере метод GetEnvironmentVariable используется для получения параметра компьютера, PSModulePath а метод SetEnvironmentVariable — для добавления C:\Program Files\Fabrikam\Modules пути к значению. The following example uses the GetEnvironmentVariable method to get the machine setting of PSModulePath and the SetEnvironmentVariable method to add the C:\Program Files\Fabrikam\Modules path to the value.