- Starting Windows PowerShell
- PowerShell Core has renamed binary
- How to Start Windows PowerShell on Earlier Versions of Windows
- From the Start Menu
- At the Command Prompt
- With Administrative privileges (Run as administrator)
- How to Start Windows PowerShell ISE on Earlier Releases of Windows
- From the Start Menu
- At the Command Prompt
- With Administrative privileges (Run as administrator)
- How to Enable Windows PowerShell ISE on Earlier Releases of Windows
- To enable Windows PowerShell Integrated Scripting Environment (ISE)
- Starting the 32-Bit Version of Windows PowerShell
- Интегрированная среда сценариев Windows PowerShell The Windows PowerShell ISE
- Поддержка Support
- Основные возможности Key Features
- Запуск интегрированной среды сценариев Windows PowerShell To start the Windows PowerShell ISE
- Получение справки в интегрированной среде сценариев Windows PowerShell To get Help in the Windows PowerShell ISE
- О скриптах About Scripts
- Краткое описание Short description
- Подробное описание Long description
- Выполнение сценария How to run a script
- Запуск с помощью PowerShell Run with PowerShell
- Выполнение сценариев на других компьютерах Running scripts on other computers
- Получить справку по сценариям Get help for scripts
- Написание сценария How to write a script
- Параметры в скриптах Parameters in scripts
- Написание справки для сценариев Writing help for scripts
- Возврат значения выхода Returning an exit value
- Область скрипта и источники с точкой Script scope and dot sourcing
- Скрипты в модулях Scripts in modules
- Другие функции сценариев Other script features
Starting Windows PowerShell
Windows PowerShell is a scripting engine .DLL that’s embedded into multiple hosts. The most common hosts you’ll start are the interactive command-line powershell.exe and the Interactive Scripting Environment powershell_ise.exe .
To start Windows PowerShellВ® on Windows ServerВ® 2012 R2, WindowsВ® 8.1, Windows Server 2012, and Windows 8, see Common Management Tasks and Navigation in Windows.
PowerShell Core has renamed binary
PowerShell Core, referred to as PowerShell, is version 6 and higher that’s open source and uses .NET Core. Supported versions are available on Windows, macOS, and Linux.
Beginning in PowerShell 6, the PowerShell binary was renamed pwsh.exe for Windows and pwsh for macOS and Linux. You can start PowerShell preview versions using pwsh-preview . For more information, see What’s New in PowerShell Core 6.0 and About pwsh.
To find cmdlet reference and installation documentation for PowerShell 7, use the following links:
Document | Link |
---|---|
Cmdlet reference | PowerShell Module Browser |
Windows installation | Installing PowerShell Core on Windows |
macOS installation | Installing PowerShell Core on macOS |
Linux installation | Installing PowerShell Core on Linux |
To view content for other PowerShell versions, see How to use the PowerShell documentation.
How to Start Windows PowerShell on Earlier Versions of Windows
This section explains how to start Windows PowerShell and Windows PowerShell Integrated Scripting Environment (ISE) on WindowsВ® 7, Windows ServerВ® 2008 R2, and Windows ServerВ® 2008. It also explains how to enable the optional feature for Windows PowerShell ISE in Windows PowerShell 2.0 on Windows ServerВ® 2008 R2 and Windows ServerВ® 2008.
Use any of the following methods to start the installed version of Windows PowerShell 3.0, or Windows PowerShell 4.0, where applicable.
From the Start Menu
- Click Start, type PowerShell, and then click Windows PowerShell.
- From the Start menu, click Start, click All Programs, click Accessories, click the Windows PowerShell folder, and then click Windows PowerShell.
At the Command Prompt
In cmd.exe, Windows PowerShell, or Windows PowerShell ISE, to start Windows PowerShell, type:
You can also use the parameters of the powershell.exe program to customize the session. For more information, see PowerShell.exe Command-Line Help.
With Administrative privileges (Run as administrator)
Click Start, type PowerShell, right-click Windows PowerShell, and then click Run as administrator.
How to Start Windows PowerShell ISE on Earlier Releases of Windows
Use any of the following methods to start Windows PowerShell ISE.
From the Start Menu
- Click Start, type ISE, and then click Windows PowerShell ISE.
- From the Start menu, click Start, click All Programs, click Accessories, click the Windows PowerShell folder, and then click Windows PowerShell ISE.
At the Command Prompt
In cmd.exe , Windows PowerShell, or Windows PowerShell ISE, to start Windows PowerShell, type:
With Administrative privileges (Run as administrator)
Click Start, type ISE, right-click Windows PowerShell ISE, and then click Run as administrator.
How to Enable Windows PowerShell ISE on Earlier Releases of Windows
In Windows PowerShell 4.0 and Windows PowerShell 3.0, Windows PowerShell ISE is enabled by default on all versions of Windows. If it isn’t already enabled, Windows Management Framework 4.0 or Windows Management Framework 3.0 enables it.
In Windows PowerShell 2.0, Windows PowerShell ISE is enabled by default on Windows 7. However, on Windows Server 2008 R2 and Windows Server 2008, it’s an optional feature.
To enable Windows PowerShell ISE in Windows PowerShell 2.0 on Windows Server 2008 R2 or Windows Server 2008, use the following procedure.
To enable Windows PowerShell Integrated Scripting Environment (ISE)
- Start Server Manager.
- Click Features and then click Add Features.
- In Select Features, click Windows PowerShell Integrated Scripting Environment (ISE).
Starting the 32-Bit Version of Windows PowerShell
When you install Windows PowerShell on a 64-bit computer, Windows PowerShell (x86), a 32-bit version of Windows PowerShell is installed in addition to the 64-bit version. When you run Windows PowerShell, the 64-bit version runs by default.
However, you might occasionally need to run Windows PowerShell (x86), such as when you’re using a module that requires the 32-bit version or when you’re connecting remotely to a 32-bit computer.
To start a 32-bit version of Windows PowerShell, use any of the following procedures.
Интегрированная среда сценариев Windows PowerShell The Windows PowerShell ISE
Интегрированная среда сценариев Windows PowerShell (ISE) является ведущим приложением для Windows PowerShell. The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. В ISE можно запускать команды, записывать и тестировать скрипты, а также выполнять их отладку в едином графическом пользовательском интерфейсе на базе Windows. In the ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphic user interface. ISE поддерживает редактирование нескольких строк, заполнение нажатием клавиши TAB, раскраску синтаксических конструкций, выборочное выполнение, контекстную справку и поддержку письма справа налево. The ISE provides multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages. Элементы меню и сочетания клавиш подходят для выполнения большинства тех же задач, которые выполняются в консоли Windows PowerShell. Menu items and keyboard shortcuts are mapped to many of the same tasks that you would do in the Windows PowerShell console. Например, при отладке скрипта в ISE вы можете щелкнуть строку кода на панели редактирования правой кнопкой мыши, чтобы задать точку останова. For example, when you debug a script in the ISE, you can right-click on a line of code in the edit pane to set a breakpoint.
Поддержка Support
ISE была впервые представлена в Windows PowerShell версии 2 и переработана в PowerShell версии 3. The ISE was first introduced with Windows PowerShell V2 and was re-designed with PowerShell V3. ISE поддерживается во всех поддерживаемых версиях Windows PowerShell до версии 5.1 включительно. The ISE is supported in all supported versions of Windows PowerShell up to and including Windows PowerShell V5.1.
Функции для ISE PowerShell больше не разрабатываются. The PowerShell ISE is no longer in active feature development. Как компонент доставки Windows эта среда по-прежнему официально поддерживается для внесения наиболее важных исправлений, связанных с безопасностью и обслуживанием. As a shipping component of Windows, it continues to be officially supported for security and high-priority servicing fixes. Пока что мы не планируем удалять ISE из Windows. We currently have no plans to remove the ISE from Windows.
ISE не поддерживается в PowerShell версии 6 и более поздних версиях. There is no support for the ISE in PowerShell v6 and beyond. Пользователям, которые ищут замену ISE, следует использовать Visual Studio Code с расширением PowerShell. Users looking for replacement for the ISE should use Visual Studio Code with the PowerShell Extension.
Основные возможности Key Features
Основные возможности в Windows PowerShell ISE являются такими: Key features in Windows PowerShell ISE include:
- редактирование нескольких строк. Чтобы вставить пустую строку под текущей строкой в области команд, нажмите клавиши SHIFT + ВВОД . Multiline editing: To insert a blank line under the current line in the Command pane, press SHIFT + ENTER .
- Выборочное выполнение. Чтобы запустить фрагмент сценария, выберите текст, который нужно запустить, и нажмите кнопку Запустить сценарий. Selective execution: To run part of a script, select the text you want to run, and then click the Run Script button. Также можно нажать клавишу F5 . Or, press F5 .
- Контекстная справка. Введите Invoke-Item и нажмите клавишу F1 . Context-sensitive help: Type Invoke-Item , and then press F1 . Откроется файл справки со ссылкой на статью о командлете Invoke-Item . The Help file opens to the article for the Invoke-Item cmdlet.
Интегрированная среда сценариев Windows PowerShell позволяет настроить некоторые аспекты его представления. The Windows PowerShell ISE lets you customize some aspects of its appearance. Она также имеет свой собственный скрипт профиля Windows PowerShell. It also has its own Windows PowerShell profile script.
Запуск интегрированной среды сценариев Windows PowerShell To start the Windows PowerShell ISE
Нажмите кнопку Пуск , выберите раздел Windows PowerShell , а затем щелкните Интегрированная среда скриптов Windows PowerShell. Click Start , select Windows PowerShell , and then click Windows PowerShell ISE. Кроме того, можно ввести powershell_ise.exe в любой командной оболочке или поле «Выполнить». Alternately, you can type powershell_ise.exe in any command shell or in the Run box.
Получение справки в интегрированной среде сценариев Windows PowerShell To get Help in the Windows PowerShell ISE
В меню Справка выберите Справка Windows PowerShell. On the Help menu, click Windows PowerShell Help. Также можно нажать клавишу F1 . Or, press F1 . В открывшемся файле будет описана интегрированная среда сценариев Windows PowerShell и Windows PowerShell, в том числе вся справка, доступная через командлет Get-Help . The file that opens describes Windows PowerShell ISE and Windows PowerShell, including all the help available from the Get-Help cmdlet.
О скриптах About Scripts
Краткое описание Short description
Описание запуска и записи скриптов в PowerShell. Describes how to run and write scripts in PowerShell.
Подробное описание Long description
Сценарий — это обычный текстовый файл, содержащий одну или несколько команд PowerShell. A script is a plain text file that contains one or more PowerShell commands. Сценарии PowerShell имеют .ps1 расширение файла. PowerShell scripts have a .ps1 file extension.
Выполнение сценария во многом похоже на выполнение командлета. Running a script is a lot like running a cmdlet. Введите путь и имя файла скрипта и используйте параметры для отправки данных и задания параметров. You type the path and file name of the script and use parameters to submit data and set options. Сценарии можно запускать на компьютере или в удаленном сеансе на другом компьютере. You can run scripts on your computer or in a remote session on a different computer.
Написание сценария сохраняет команду для последующего использования и упрощает совместное использование с другими пользователями. Writing a script saves a command for later use and makes it easy to share with others. Что самое важное, это позволяет выполнять команды просто путем ввода пути скрипта и имени файла. Most importantly, it lets you run the commands simply by typing the script path and the filename. Скрипты могут быть простыми как одной командой в файле, так и сложной программой. Scripts can be as simple as a single command in a file or as extensive as a complex program.
Сценарии имеют дополнительные функции, такие как #Requires Специальный комментарий, использование параметров, поддержка разделов данных и цифровая подпись для обеспечения безопасности. Scripts have additional features, such as the #Requires special comment, the use of parameters, support for data sections, and digital signing for security. Также можно написать разделы справки для скриптов и для любых функций в скрипте. You can also write Help topics for scripts and for any functions in the script.
Выполнение сценария How to run a script
Прежде чем можно будет запустить сценарий в Windows, необходимо изменить политику выполнения PowerShell по умолчанию. Before you can run a script on Windows, you need to change the default PowerShell execution policy. Политика выполнения не применяется к PowerShell, работающему на платформах, отличных от Windows. Execution policy does not apply to PowerShell running on non-Windows platforms.
Политика выполнения по умолчанию Restricted предотвращает выполнение всех скриптов, включая скрипты, которые вы пишете на локальном компьютере. The default execution policy, Restricted , prevents all scripts from running, including scripts that you write on the local computer. Подробнее см. в разделе about_Execution_Policies. For more information, see about_Execution_Policies.
Политика выполнения сохраняется в реестре, поэтому ее необходимо изменить только один раз на каждом компьютере. The execution policy is saved in the registry, so you need to change it only once on each computer.
Чтобы изменить политику выполнения, используйте следующую процедуру. To change the execution policy, use the following procedure.
В командной строке введите: At the command prompt, type:
Изменение вступает в силу немедленно. The change is effective immediately.
Чтобы выполнить сценарий, введите полное имя файла скрипта и полный путь к нему. To run a script, type the full name and the full path to the script file.
Например, чтобы запустить сценарий Get-ServiceLog.ps1 в каталоге C:\Scripts, введите: For example, to run the Get-ServiceLog.ps1 script in the C:\Scripts directory, type:
Чтобы выполнить сценарий в текущем каталоге, введите путь к текущему каталогу или используйте точку для представления текущего каталога, после чего следует обратная косая черта ( .\ ). To run a script in the current directory, type the path to the current directory, or use a dot to represent the current directory, followed by a path backslash ( .\ ).
Например, чтобы запустить сценарий ServicesLog.ps1 в локальном каталоге, введите: For example, to run the ServicesLog.ps1 script in the local directory, type:
Если у скрипта есть параметры, введите параметры и значения параметров после имени файла скрипта. If the script has parameters, type the parameters and parameter values after the script filename.
Например, следующая команда использует параметр ServiceName скрипта Get-ServiceLog, чтобы запросить журнал действия службы удаленного управления Windows. For example, the following command uses the ServiceName parameter of the Get-ServiceLog script to request a log of WinRM service activity.
В качестве функции безопасности PowerShell не выполняет сценарии при двойном щелчке значка скрипта в проводнике или при вводе имени сценария без полного пути, даже если сценарий находится в текущем каталоге. As a security feature, PowerShell does not run scripts when you double-click the script icon in File Explorer or when you type the script name without a full path, even when the script is in the current directory. Дополнительные сведения о выполнении команд и сценариев в PowerShell см. в разделе about_Command_Precedence. For more information about running commands and scripts in PowerShell, see about_Command_Precedence.
Запуск с помощью PowerShell Run with PowerShell
Начиная с PowerShell 3,0 можно запускать сценарии из проводника. Beginning in PowerShell 3.0, you can run scripts from File Explorer.
Чтобы использовать функцию «Запуск с помощью PowerShell», сделайте следующее: To use the «Run with PowerShell» feature:
Запустите проводник, щелкните правой кнопкой мыши имя файла скрипта и выберите команду «запустить с помощью PowerShell». Run File Explorer, right-click the script filename and then select «Run with PowerShell».
Функция «запустить с помощью PowerShell» предназначена для выполнения скриптов, которые не имеют обязательных параметров и не возвращают выходные данные в командную строку. The «Run with PowerShell» feature is designed to run scripts that do not have required parameters and do not return output to the command prompt.
Дополнительные сведения см. в разделе about_Run_With_PowerShell. For more information, see about_Run_With_PowerShell.
Выполнение сценариев на других компьютерах Running scripts on other computers
Чтобы запустить сценарий на одном или нескольких удаленных компьютерах, используйте параметр FilePath Invoke-Command командлета. To run a script on one or more remote computers, use the FilePath parameter of the Invoke-Command cmdlet.
Введите путь и имя файла скрипта в качестве значения параметра FilePath . Enter the path and filename of the script as the value of the FilePath parameter. Скрипт должен находиться на локальном компьютере или в каталоге, к которому локальный компьютер может получить доступ. The script must reside on the local computer or in a directory that the local computer can access.
Следующая команда запускает Get-ServiceLog.ps1 сценарий на удаленных компьютерах с именем Server01 и Server02. The following command runs the Get-ServiceLog.ps1 script on the remote computers named Server01 and Server02.
Получить справку по сценариям Get help for scripts
Командлет Get-Help получает разделы справки для скриптов, а также для командлетов и других типов команд. The Get-Help cmdlet gets the help topics for scripts as well as for cmdlets and other types of commands. Чтобы получить раздел справки для скрипта, введите, Get-Help за которым следует путь и имя файла скрипта. To get the help topic for a script, type Get-Help followed by the path and filename of the script. Если путь к скрипту находится в Path переменной среды, путь можно опустить. If the script path is in your Path environment variable, you can omit the path.
Например, чтобы получить справку по сценарию ServicesLog.ps1, введите: For example, to get help for the ServicesLog.ps1 script, type:
Написание сценария How to write a script
Скрипт может содержать любые допустимые команды PowerShell, в том числе отдельные команды, команды, использующие конвейер, функции и управляющие структуры, такие как операторы If и циклы for. A script can contain any valid PowerShell commands, including single commands, commands that use the pipeline, functions, and control structures such as If statements and For loops.
Чтобы написать сценарий, откройте новый файл в текстовом редакторе, введите команды и сохраните их в файле с допустимым именем файла с .ps1 расширением. To write a script, open a new file in a text editor, type the commands, and save them in a file with a valid filename with the .ps1 file extension.
Следующий пример представляет собой простой сценарий, который получает службы, работающие в текущей системе, и сохраняет их в файл журнала. The following example is a simple script that gets the services that are running on the current system and saves them to a log file. Имя файла журнала создается с текущей даты. The log filename is created from the current date.
Чтобы создать этот скрипт, откройте текстовый редактор или редактор скриптов, введите следующие команды, а затем сохраните их в файле с именем ServiceLog.ps1 . To create this script, open a text editor or a script editor, type these commands, and then save them in a file named ServiceLog.ps1 .
Параметры в скриптах Parameters in scripts
Чтобы определить параметры в скрипте, используйте инструкцию param. To define parameters in a script, use a Param statement. Param Инструкция должна быть первой инструкцией в скрипте, за исключением комментариев и любых #Require инструкций. The Param statement must be the first statement in a script, except for comments and any #Require statements.
Параметры сценария работают как параметры функции. Script parameters work like function parameters. Значения параметров доступны для всех команд в скрипте. The parameter values are available to all of the commands in the script. Все функции параметров функций, включая атрибут Parameter и его именованные аргументы, также допустимы в скриптах. All of the features of function parameters, including the Parameter attribute and its named arguments, are also valid in scripts.
При выполнении скрипта пользователи заменяют параметры после имени скрипта. When running the script, script users type the parameters after the script name.
В следующем примере показан Test-Remote.ps1 скрипт с параметром ComputerName . The following example shows a Test-Remote.ps1 script that has a ComputerName parameter. Обе функции сценария могут обращаться к значению параметра ComputerName . Both of the script functions can access the ComputerName parameter value.
Чтобы выполнить этот скрипт, введите имя параметра после имени скрипта. To run this script, type the parameter name after the script name. Пример: For example:
Дополнительные сведения о инструкции Param и параметрах функции см. в разделе about_Functions и about_Functions_Advanced_Parameters. For more information about the Param statement and the function parameters, see about_Functions and about_Functions_Advanced_Parameters.
Написание справки для сценариев Writing help for scripts
Раздел справки для скрипта можно написать с помощью любого из двух следующих методов. You can write a help topic for a script by using either of the two following methods:
Comment-Based справки по сценариям Comment-Based Help for Scripts
Создайте раздел справки, используя специальные ключевые слова в комментариях. Create a Help topic by using special keywords in the comments. Чтобы создать справку на основе комментариев для сценария, необходимо поместить комментарии в начало или в конец файла скрипта. To create comment-based Help for a script, the comments must be placed at the beginning or end of the script file. Дополнительные сведения о справке на основе комментариев см. в разделе about_Comment_Based_Help. For more information about comment-based Help, see about_Comment_Based_Help.
XML-Based справки по сценариям XML-Based Help for Scripts
Создайте раздел справки на основе XML, например тип, который обычно создается для командлетов. Create an XML-based Help topic, such as the type that is typically created for cmdlets. При преобразовании разделов справки на несколько языков требуется справка на основе XML. XML-based Help is required if you are translating Help topics into multiple languages.
Чтобы связать скрипт с разделом справки на основе XML, используйте. Ключевое слово комментария справки Екстерналхелп. To associate the script with the XML-based Help topic, use the .ExternalHelp Help comment keyword. Дополнительные сведения о ключевом слове Екстерналхелп см. в разделе about_Comment_Based_Help. For more information about the ExternalHelp keyword, see about_Comment_Based_Help. Дополнительные сведения о справке на основе XML см. в разделе как написать справку по командлетам. For more information about XML-based help, see How to Write Cmdlet Help.
Возврат значения выхода Returning an exit value
По умолчанию скрипты не возвращают состояние выхода при завершении сценария. By default, scripts do not return an exit status when the script ends. exit Для возврата кода выхода из скрипта необходимо использовать инструкцию. You must use the exit statement to return an exit code from a script. По умолчанию exit инструкция возвращает 0 . By default, the exit statement returns 0 . Можно указать числовое значение, чтобы вернуть другое состояние выхода. You can provide a numeric value to return a different exit status. Ненулевое значение кода выхода обычно сигнализирует об ошибке. A nonzero exit code typically signals a failure.
В Windows допускается любое число между [int]::MinValue и [int]::MaxValue . On Windows, any number between [int]::MinValue and [int]::MaxValue is allowed.
В UNIX разрешены только положительные числа в диапазоне от [byte]::MinValue (0) до [byte]::MaxValue (255). On Unix, only positive numbers between [byte]::MinValue (0) and [byte]::MaxValue (255) are allowed. Отрицательное число в диапазоне от -1 до -255 автоматически преобразуется в положительное число путем добавления A negative number in the range of -1 through -255 is automatically translated into a positive number by adding 256. Например, -2 преобразуется в 254 . For example, -2 is transformed to 254 .
В PowerShell exit инструкция задает значение $LASTEXITCODE переменной. In PowerShell, the exit statement sets the value of the $LASTEXITCODE variable. В командной оболочке Windows (cmd.exe) оператор Exit задает значение %ERRORLEVEL% переменной среды. In the Windows Command Shell (cmd.exe), the exit statement sets the value of the %ERRORLEVEL% environment variable.
Любой аргумент, который не является числовым или вне диапазона, зависящего от платформы, преобразуется в значение 0 . Any argument that is non-numeric or outside the platform-specific range is translated to the value of 0 .
Область скрипта и источники с точкой Script scope and dot sourcing
Каждый скрипт выполняется в отдельной области. Each script runs in its own scope. Функции, переменные, псевдонимы и диски, созданные в сценарии, существуют только в области скрипта. The functions, variables, aliases, and drives that are created in the script exist only in the script scope. Доступ к этим элементам или их значениям в области, в которой выполняется скрипт, невозможен. You cannot access these items or their values in the scope in which the script runs.
Чтобы выполнить скрипт в другой области, можно указать область, например Global или local, или создать точку для скрипта. To run a script in a different scope, you can specify a scope, such as Global or Local, or you can dot source the script.
Функция «с точкой» позволяет запускать скрипт в текущей области, а не в области скрипта. The dot sourcing feature lets you run a script in the current scope instead of in the script scope. При запуске скрипта, который имеет точку с точкой, команды в скрипте выполняются так, будто были введены в командной строке. When you run a script that is dot sourced, the commands in the script run as though you had typed them at the command prompt. Функции, переменные, псевдонимы и диски, создаваемые сценарием, создаются в области, в которой выполняется работа. The functions, variables, aliases, and drives that the script creates are created in the scope in which you are working. После выполнения скрипта можно использовать созданные элементы и получить доступ к их значениям в сеансе. After the script runs, you can use the created items and access their values in your session.
Чтобы создать точку скрипта для исходного кода, введите точку (.) и пробел перед путем к сценарию. To dot source a script, type a dot (.) and a space before the script path.
Пример: For example:
или диспетчер конфигурации служб or
После UtilityFunctions.ps1 выполнения скрипта функции и переменные, создаваемые сценарием, добавляются в текущую область. After the UtilityFunctions.ps1 script runs, the functions and variables that the script creates are added to the current scope.
Например, UtilityFunctions.ps1 Скрипт создает New-Profile функцию и $ProfileName переменную. For example, the UtilityFunctions.ps1 script creates the New-Profile function and the $ProfileName variable.
При запуске UtilityFunctions.ps1 скрипта в собственной области скрипта New-Profile функция и $ProfileName переменная существуют только во время выполнения скрипта. If you run the UtilityFunctions.ps1 script in its own script scope, the New-Profile function and the $ProfileName variable exist only while the script is running. При завершении работы скрипта удаляется функция и переменная, как показано в следующем примере. When the script exits, the function and variable are removed, as shown in the following example.
Когда вы подаете скрипту точку и запускаете его, сценарий создает New-Profile функцию и $ProfileName переменную в своем сеансе в вашей области. When you dot source the script and run it, the script creates the New-Profile function and the $ProfileName variable in your session in your scope. После выполнения скрипта можно использовать New-Profile функцию в сеансе, как показано в следующем примере. After the script runs, you can use the New-Profile function in your session, as shown in the following example.
Дополнительные сведения об области действия см. в разделе about_Scopes. For more information about scope, see about_Scopes.
Скрипты в модулях Scripts in modules
Модуль — это набор связанных ресурсов PowerShell, которые можно распространять как единое целое. A module is a set of related PowerShell resources that can be distributed as a unit. Вы можете использовать модули для организации скриптов, функций и других ресурсов. You can use modules to organize your scripts, functions, and other resources. Можно также использовать модули для распространения кода среди других пользователей и получения кода из надежных источников. You can also use modules to distribute your code to others, and to get code from trusted sources.
Можно включить скрипты в модули или создать модуль скрипта, который представляет собой модуль, полностью или в основном содержащий скрипт и вспомогательные ресурсы. You can include scripts in your modules, or you can create a script module, which is a module that consists entirely or primarily of a script and supporting resources. Модуль скрипта — это просто сценарий с расширением файла PSM1. A script module is just a script with a .psm1 file extension.
Дополнительные сведения о модулях см. в разделе about_Modules. For more information about modules, see about_Modules.
Другие функции сценариев Other script features
В PowerShell есть много полезных функций, которые можно использовать в скриптах. PowerShell has many useful features that you can use in scripts.
#Requires — Можно использовать #Requires инструкцию, чтобы предотвратить выполнение скрипта без указанных модулей или оснасток и заданную версию PowerShell. #Requires — You can use a #Requires statement to prevent a script from running without specified modules or snap-ins and a specified version of PowerShell. Дополнительные сведения см. в разделе about_Requires. For more information, see about_Requires.
$PSCommandPath — Содержит полный путь и имя выполняемого скрипта. $PSCommandPath — Contains the full path and name of the script that is being run. Этот параметр допустим во всех скриптах. This parameter is valid in all scripts. Эта автоматическая переменная появилась в PowerShell 3,0. This automatic variable is introduced in PowerShell 3.0.
$PSScriptRoot — Содержит каталог, из которого выполняется скрипт. $PSScriptRoot — Contains the directory from which a script is being run. В PowerShell 2,0 эта переменная допустима только в модулях скриптов ( .psm1 ). In PowerShell 2.0, this variable is valid only in script modules ( .psm1 ). Начиная с PowerShell 3,0, он действителен во всех скриптах. Beginning in PowerShell 3.0, it is valid in all scripts.
$MyInvocation — $MyInvocation Автоматическая переменная содержит сведения о текущем скрипте, включая сведения о том, как он был запущен или вызван. $MyInvocation — The $MyInvocation automatic variable contains information about the current script, including information about how it was started or «invoked.» Эту переменную и ее свойства можно использовать для получения сведений о скрипте во время его выполнения. You can use this variable and its properties to get information about the script while it is running. Например, $MyInvocation . Переменная Микомманд. path содержит путь и имя файла скрипта. For example, the $MyInvocation .MyCommand.Path variable contains the path and filename of the script. $MyInvocation . Строка содержит команду, которая запустила скрипт, включая все параметры и значения. $MyInvocation .Line contains the command that started the script, including all parameters and values.
Начиная с PowerShell 3,0, $MyInvocation имеет два новых свойства, которые предоставляют сведения о скрипте, который вызывал или вызывает текущий скрипт. Beginning in PowerShell 3.0, $MyInvocation has two new properties that provide information about the script that called or invoked the current script. Значения этих свойств заполняются только в том случае, если вызывающий элемент или вызвавший объект является сценарием. The values of these properties are populated only when the invoker or caller is a script.
Пскоммандпас содержит полный путь и имя скрипта, который вызывал или вызывает текущий скрипт. PSCommandPath contains the full path and name of the script that called or invoked the current script.
PSScriptRoot содержит каталог скрипта, вызвавшего или вызвавшего текущий скрипт. PSScriptRoot contains the directory of the script that called or invoked the current script.
В отличие от $PSCommandPath и $PSScriptRoot автоматических переменных, содержащих сведения о текущем скрипте, свойства пскоммандпас и PSScriptRoot этой $MyInvocation переменной содержат сведения о скрипте, вызвавшем текущий скрипт. Unlike the $PSCommandPath and $PSScriptRoot automatic variables, which contain information about the current script, the PSCommandPath and PSScriptRoot properties of the $MyInvocation variable contain information about the script that called the current script.
Разделы данных. Вы можете использовать Data ключевое слово для разделения данных из логики в скриптах. Data sections — You can use the Data keyword to separate data from logic in scripts. Разделы данных также могут упростить локализацию. Data sections can also make localization easier. Дополнительные сведения см. в разделе about_Data_Sections и about_Script_Internationalization. For more information, see about_Data_Sections and about_Script_Internationalization.
Подпись скрипта. Вы можете добавить цифровую подпись к сценарию. Script Signing — You can add a digital signature to a script. В зависимости от политики выполнения можно использовать цифровые подписи для ограничения выполнения скриптов, которые могут включать ненадежные команды. Depending on the execution policy, you can use digital signatures to restrict the running of scripts that could include unsafe commands. Дополнительные сведения см. в разделе about_Execution_Policies и about_Signing. For more information, see about_Execution_Policies and about_Signing.