Windows powershell install modules

Установка модуля PowerShell Installing a PowerShell Module

После создания модуля PowerShell вы, вероятно, захотите установить модуль в системе, чтобы его могли использовать не только вы, но и другие пользователи. After you have created your PowerShell module, you will likely want to install the module on a system, so that you or others may use it. В целом, этот процесс включает копирование файлов модулей (файлы PSM1 или двоичной сборки, манифеста модуля и другие связанные файлы) в каталог на этом компьютере. Generally speaking, this consists of copying the module files (ie, the .psm1, or the binary assembly, the module manifest, and any other associated files) onto a directory on that computer. Для очень маленького проекта это может быть просто копирование и вставка файлов с помощью проводника Windows на один удаленный компьютер. Но для более крупных решений может потребоваться более сложный процесс установки. For a very small project, this may be as simple as copying and pasting the files with Windows Explorer onto a single remote computer; however, for larger solutions you may wish to use a more sophisticated installation process. Независимо от того, как вы устанавливаете модуль в системе, PowerShell поддерживает ряд методов, с помощью которых пользователи могут находить и использовать ваши модули. Regardless of how you get your module onto the system, PowerShell can use a number of techniques that will let users find and use your modules. Следовательно, основная задача установки — сделать так, чтобы ваш модуль был доступным для PowerShell. Therefore, the main issue for installation is ensuring that PowerShell will be able to find your module. Дополнительные сведения см. в статье Импорт модуля PowerShell. For more information, see Importing a PowerShell Module.

Правила установки модулей Rules for Installing Modules

Следующие сведения относятся ко всем модулям, включая модули, созданные для собственного использования, получаемые от других сторон и предоставляемые другим пользователям. The following information pertains to all modules, including modules that you create for your own use, modules that you get from other parties, and modules that you distribute to others.

Установка модулей в PSModulePath Install Modules in PSModulePath

По возможности устанавливайте все модули по пути, указанному в переменной среды PSModulePath, или добавьте путь к модулю в значение переменной среды PSModulePath. Whenever possible, install all modules in a path that is listed in the PSModulePath environment variable or add the module path to the PSModulePath environment variable value.

Переменная среды PSModulePath ($Env:PSModulePath) содержит сведения о расположении модулей Windows PowerShell. The PSModulePath environment variable ($Env:PSModulePath) contains the locations of Windows PowerShell modules. Командлеты используют значение этой переменной среды для поиска модулей. Cmdlets rely on the value of this environment variable to find modules.

По умолчанию значение переменной среды PSModulePath содержит следующие системные и пользовательские каталоги модулей, но вы можете добавлять и изменять это значение. By default, the PSModulePath environment variable value contains the following system and user module directories, but you can add to and edit the value.

$PSHome\Modules (%Windir%\System32\WindowsPowerShell\v1.0\Modules) $PSHome\Modules (%Windir%\System32\WindowsPowerShell\v1.0\Modules)

Это расположение зарезервировано для модулей, поставляемых с Windows. This location is reserved for modules that ship with Windows. Не устанавливайте модули в это расположение. Do not install modules to this location.

$Home\Documents\WindowsPowerShell\Modules (%UserProfile%\Documents\WindowsPowerShell\Modules) $Home\Documents\WindowsPowerShell\Modules (%UserProfile%\Documents\WindowsPowerShell\Modules)

$Env:ProgramFiles\WindowsPowerShell\Modules (%ProgramFiles%\WindowsPowerShell\Modules) $Env:ProgramFiles\WindowsPowerShell\Modules (%ProgramFiles%\WindowsPowerShell\Modules)

Чтобы получить значение переменной среды PSModulePath, используйте одну из следующих команд. To get the value of the PSModulePath environment variable, use either of the following commands.

Чтобы добавить путь к модулю в значение переменной среды PSModulePath, используйте следующий формат команды. To add a module path to value of the PSModulePath environment variable value, use the following command format. В этом формате используется метод SetEnvironmentVariable класса System.Environment, чтобы сделать изменение переменной среды PSModulePath независимым от сеанса. This format uses the SetEnvironmentVariable method of the System.Environment class to make a session-independent change to the PSModulePath environment variable.

Читайте также:  Узнать все открытые порты linux

После добавления пути в PSModulePath выполните рассылку сообщения окружения об изменении. Once you have added the path to PSModulePath, you should broadcast an environment message about the change. Так другие приложения, например оболочка, смогут поддерживать эти изменения. Broadcasting the change allows other applications, such as the shell, to pick up the change. Для этого код установки продукта должен отправить сообщение WM_SETTINGCHANGE с параметром lParam , для которого задана строка Environment. To broadcast the change, have your product installation code send a WM_SETTINGCHANGE message with lParam set to the string «Environment». Не забудьте отправить сообщение после того, как код установки модуля обновит PSModulePath. Be sure to send the message after your module installation code has updated PSModulePath.

Использование правильного имени каталога модулей Use the Correct Module Directory Name

Модуль с правильным форматом — это модуль, хранящийся в каталоге, имя которого совпадает с базовым именем хотя бы одного файла в каталоге модуля. A well-formed module is a module that is stored in a directory that has the same name as the base name of at least one file in the module directory. Если формат модуля неправильный, Windows PowerShell не распознает его как модуль. If a module is not well-formed, Windows PowerShell does not recognize it as a module.

Базовое имя файла — это имя файла без расширения. The «base name» of a file is the name without the file name extension. В модуле с правильным форматом имя каталога, содержащего файлы модулей, должно совпадать с базовым именем хотя бы одного файла в модуле. In a well-formed module, the name of the directory that contains the module files must match the base name of at least one file in the module.

Например, в примере модуля Fabrikam каталог, содержащий файлы модулей, называется Fabrikam, и хотя бы один файл имеет базовое имя Fabrikam. For example, in the sample Fabrikam module, the directory that contains the module files is named «Fabrikam» and at least one file has the «Fabrikam» base name. В этом случае и Fabrikam.psd1, и Fabrikam.dll имеют базовое имя Fabrikam. In this case, both Fabrikam.psd1 and Fabrikam.dll have the «Fabrikam» base name.

Результат неправильной установки Effect of Incorrect Installation

Если модуль имеет неправильный формат и его расположение не включено в значение переменной среды PSModulePath, основные функции обнаружения Windows PowerShell, описанные ниже, не будут работать. If the module is not well-formed and its location is not included in the value of the PSModulePath environment variable, basic discovery features of Windows PowerShell, such as the following, do not work.

Функция автоматической загрузки модуля не сможет автоматически импортировать модуль. The Module Auto-Loading feature cannot import the module automatically.

Параметр ListAvailable командлета Get-Module не сможет найти модуль. The ListAvailable parameter of the Get-Module cmdlet cannot find the module.

Командлет Import-Module не сможет найти модуль. The Import-Module cmdlet cannot find the module. Чтобы импортировать модуль, необходимо указать полный путь к файлу корневого модуля или файлу манифеста модуля. To import the module, you must provide the full path to the root module file or module manifest file.

Дополнительные функции, описанные ниже, не будут работать, если модуль не импортируется в сеанс. Additional features, such as the following, do not work unless the module is imported into the session. В модулях с правильным форматом в переменной среды PSModulePath эти функции будут работать, даже если модуль не импортируется в сеанс. In well-formed modules in the PSModulePath environment variable, these features work even when the module is not imported into the session.

Командлет Get-Command не сможет найти команды в модуле. The Get-Command cmdlet cannot find commands in the module.

Командлеты Update-Help и Save-Help не смогут обновить или сохранить справку для модуля. The Update-Help and Save-Help cmdlets cannot update or save help for the module.

Командлет Show-Command не сможет найти и отобразить команды в модуле. The Show-Command cmdlet cannot find and display the commands in the module.

Команды в модуле будут отсутствовать в окне Show-Command в интегрированной среде скриптов Windows PowerShell (ISE). The commands in the module are missing from the Show-Command window in Windows PowerShell Integrated Scripting Environment (ISE).

Читайте также:  Linux выделить несколько файлов

Расположение для установки модулей Where to Install Modules

В этом разделе описывается, где в файловой системе устанавливаются модули Windows PowerShell. This section explains where in the file system to install Windows PowerShell modules. Расположение зависит от того, как используется модуль. The location depends on how the module is used.

Установка модулей для определенного пользователя Installing Modules for a Specific User

Если вы создаете собственный модуль или получаете модуль от другой стороны, например с веб-сайта сообщества Windows PowerShell, и вам нужно, чтобы модуль был доступен только для вашей учетной записи пользователя, установите модуль в пользовательском каталоге модулей. If you create your own module or get a module from another party, such as a Windows PowerShell community website, and you want the module to be available for your user account only, install the module in your user-specific Modules directory.

Этот каталог добавляется в значение переменной среды PSModulePath по умолчанию. The user-specific Modules directory is added to the value of the PSModulePath environment variable by default.

Установка модулей для всех пользователей в программных файлах Installing Modules for all Users in Program Files

Если вам нужно, чтобы модуль был доступен для всех учетных записей пользователей на компьютере, установите модуль в папку с программными файлами. If you want a module to be available to all user accounts on the computer, install the module in the Program Files location.

Это расположение добавляется в значение переменной среды PSModulePath по умолчанию в Windows PowerShell 4.0 и более поздних версиях. The Program Files location is added to the value of the PSModulePath environment variable by default in Windows PowerShell 4.0 and later. Для более ранних версий Windows PowerShell можно вручную создать расположение программных файлов (%ProgramFiles%\WindowsPowerShell\Modules) и добавить этот путь в переменную среды PSModulePath, как описано выше. For earlier versions of Windows PowerShell, you can manually create the Program Files location (%ProgramFiles%\WindowsPowerShell\Modules) and add this path to your PSModulePath environment variable as described above.

Установка модулей в каталоге продукта Installing Modules in a Product Directory

Если вы предоставляете модуль другим сторонам, используйте каталог с программными файлами по умолчанию, как описано выше, или создайте собственный подкаталог для компании или продукта в каталоге %ProgramFiles%. If you are distributing the module to other parties, use the default Program Files location described above, or create your own company-specific or product-specific subdirectory of the %ProgramFiles% directory.

Например вымышленная компания Fabrikam Technologies предоставляет модуль Windows PowerShell для своего продукта Fabrikam Manager. For example, Fabrikam Technologies, a fictitious company, is shipping a Windows PowerShell module for their Fabrikam Manager product. Установщик модуля создает подкаталог Modules в подкаталоге продукта Fabrikam Manager. Their module installer creates a Modules subdirectory in the Fabrikam Manager product subdirectory.

Чтобы включить функции обнаружения модулей Windows PowerShell для поиска модуля Fabrikam, установщик модуля Fabrikam добавляет расположение модуля в значение переменной среды PSModulePath. To enable the Windows PowerShell module discovery features to find the Fabrikam module, the Fabrikam module installer adds the module location to the value of the PSModulePath environment variable.

Установка модулей в каталоге с общими файлами Installing Modules in the Common Files Directory

Если модуль используется несколькими компонентами или версиями продукта, установите модуль в подкаталог для модуля в подкаталоге %ProgramFiles%\Common Files\Modules. If a module is used by multiple components of a product or by multiple versions of a product, install the module in a module-specific subdirectory of the %ProgramFiles%\Common Files\Modules subdirectory.

В следующем примере модуль Fabrikam устанавливается в подкаталог Fabrikam в подкаталоге %ProgramFiles%\Common Files\Modules . In the following example, the Fabrikam module is installed in a Fabrikam subdirectory of the %ProgramFiles%\Common Files\Modules subdirectory. Обратите внимание, что каждый модуль находится в отдельном подкаталоге в подкаталоге Modules. Note that each module resides in its own subdirectory in the Modules subdirectory.

Затем установщик проверяет, что значение переменной среды PSModulePath содержит путь к подкаталогу модуля с общими файлами. Then, the installer assures the value of the PSModulePath environment variable includes the path of the common files modules subdirectory.

Установка нескольких версий модуля Installing Multiple Versions of a Module

Чтобы установить несколько версий одного модуля, выполните следующую процедуру. To install multiple versions of the same module, use the following procedure.

  1. Создайте каталог для каждой версии модуля. Create a directory for each version of the module. Включите номер версии в имя каталога. Include the version number in the directory name.
  2. Создайте манифест модуля для каждой версии модуля. Create a module manifest for each version of the module. В качестве значения ключа ModuleVersion в манифесте укажите номер версии модуля. In the value of the ModuleVersion key in the manifest, enter the module version number. Сохраните файл манифеста (.psd1) в каталоге для версии модуля. Save the manifest file (.psd1) in the version-specific directory for the module.
  3. Добавьте путь к корневой папке модуля в значение переменной среды PSModulePath, как показано в следующих примерах. Add the module root folder path to the value of the PSModulePath environment variable, as shown in the following examples.
Читайте также:  Kyocera fs 1025mfp драйвер windows 10 64 bit

Чтобы импортировать определенную версию модуля, пользователь может использовать параметры MinimumVersion или RequiredVersion командлета Import-Module. To import a particular version of the module, the end-user can use the MinimumVersion or RequiredVersion parameters of the Import-Module cmdlet.

Например, если модуль Fabrikam доступен в версиях 8.0 и 9.0, структура каталогов модуля Fabrikam может выглядеть следующим образом: For example, if the Fabrikam module is available in versions 8.0 and 9.0, the Fabrikam module directory structure might resemble the following.

Установщик добавляет оба пути к модулю в значение переменной среды PSModulePath. The installer adds both of the module paths to the PSModulePath environment variable value.

После выполнения этих действий параметр ListAvailable командлета Get-Module получает оба модуля Fabrikam. When these steps are complete, the ListAvailable parameter of the Get-Module cmdlet gets both of the Fabrikam modules. Чтобы импортировать определенный модуль, используйте параметры MinimumVersion или RequiredVersion командлета Import-Module. To import a particular module, use the MinimumVersion or RequiredVersion parameters of the Import-Module cmdlet.

Если оба модуля, которые содержат командлеты с одинаковыми именами, импортируются в один сеанс, в этом сеансе будут доступными командлеты, импортированные последними. If both modules are imported into the same session, and the modules contain cmdlets with the same names, the cmdlets that are imported last are effective in the session.

Обработка конфликтов имен команд Handling Command Name Conflicts

Конфликты имен команд могут возникать, когда команды, экспортируемые модулем, имеют те же имена, что и команды в сеансе пользователя. Command name conflicts can occur when the commands that a module exports have the same name as commands in the user’s session.

Если сеанс содержит две команды с одинаковым именем, Windows PowerShell выполняет команду согласно приоритету по типу. When a session contains two commands that have the same name, Windows PowerShell runs the command type that takes precedence. Если сеанс содержит две команды с одинаковыми именем и типом, Windows PowerShell выполняет команду, которая была добавлена в сеанс последней. When a session contains two commands that have the same name and the same type, Windows PowerShell runs the command that was added to the session most recently. Чтобы выполнить команду, которая не выполняется по умолчанию, пользователи могут определить ее имя, используя имя модуля. To run a command that is not run by default, users can qualify the command name with the module name.

Например, если сеанс содержит функцию Get-Date и командлет Get-Date , Windows PowerShell по умолчанию выполняет эту функцию. For example, if the session contains a Get-Date function and the Get-Date cmdlet, Windows PowerShell runs the function by default. Чтобы выполнить командлет, укажите перед командой имя модуля, например: To run the cmdlet, preface the command with the module name, such as:

Чтобы предотвратить конфликты имен, авторы модулей могут использовать ключ DefaultCommandPrefix в манифесте модуля, чтобы указать префикс существительного для всех команд, экспортируемых из модуля. To prevent name conflicts, module authors can use the DefaultCommandPrefix key in the module manifest to specify a noun prefix for all commands exported from the module.

Чтобы применить альтернативный префикс, пользователи могут использовать параметр Prefix командлета Import-Module . Users can use the Prefix parameter of the Import-Module cmdlet to use an alternate prefix. Значение параметра Prefix имеет приоритет над значением ключа DefaultCommandPrefix. The value of the Prefix parameter takes precedence over the value of the DefaultCommandPrefix key.

Оцените статью