- Windows PowerShell Reference
- Developer Audience
- Windows PowerShell Resources
- Основные понятия рабочего процесса Windows PowerShell Windows PowerShell Workflow Concepts
- Рабочие процессы Windows PowerShell Windows PowerShell Workflows
- Основная структура Basic Structure
- Именование Naming
- Ограничения Limitations
- Действия Activities
- Модули интеграции Integration Modules
- Параллельное выполнение Parallel Execution
- Контрольные точки Checkpoints
- Приостановка Runbook Suspend a Runbook
- InlineScript (Встроенный сценарий) InlineScript
Windows PowerShell Reference
Windows PowerShell is a Microsoft .NET Framework-connected environment designed for administrative automation. Windows PowerShell provides a new approach to building commands, composing solutions, and creating graphical user interface-based management tools.
Windows PowerShell enables a system administrator to automate the administration of system resources by the execution of commands either directly or through scripts.
Developer Audience
The Windows PowerShell Software Development Kit (SDK) is written for command developers who require reference information about the APIs provided by Windows PowerShell. Command developers use Windows PowerShell to create both commands and providers that extend the tasks that can be performed by Windows PowerShell.
Windows PowerShell Resources
In addition to the Windows PowerShell SDK, the following resources provide more information.
Getting Started with Windows PowerShell Provides an introduction to Windows PowerShell: the language, the cmdlets, the providers, and the use of objects.
Writing a Windows PowerShell Module Provides information and examples for administrators, script developers, and cmdlet developers who need to package and distribute their Windows PowerShell solutions using Windows PowerShell modules.
Writing a Windows PowerShell Cmdlet Provides information and code examples for program managers who are designing cmdlets and for developers who are implementing cmdlet code.
Windows PowerShell Team Blog The best resource for learning from and collaborating with other Windows PowerShell users. Read the Windows PowerShell Team blog, and then join the Windows PowerShell User Forum (microsoft.public.windows.powershell). Use Windows Live Search to find other Windows PowerShell blogs and resources. Then, as you develop your expertise, freely contribute your ideas.
PowerShell module browser Provides the latest versions of the command-line Help topics.
Основные понятия рабочего процесса Windows PowerShell Windows PowerShell Workflow Concepts
Эта версия Service Management Automation (SMA) достигла конца поддержки, мы рекомендуем выполнить обновление до SMA 2019. This version of Service Management Automation (SMA) has reached the end of support, we recommend you to upgrade to SMA 2019.
Один Тип модуля Runbook для Service Management Automation основан на рабочих процессах Windows PowerShell. One type of runbook for Service Management Automation is based on Windows PowerShell Workflows. В этом разделе содержится краткий обзор критически важных функций рабочих процессов, общих для модулей Runbook службы автоматизации. This section provides a brief overview of critical features of workflows that are common to Automation runbooks. Дополнительные сведения о рабочих процессах см. в статье Общие сведения о рабочем процессе Windows PowerShell. Complete details on workflows are available in Getting Started with Windows PowerShell Workflow.
Структура модуля Runbook идентична между модулями Runbook для Service Management Automation и для Microsoft Azure автоматизации , хотя они обычно работают с различными ресурсами. The runbook structure is identical between runbooks for Service Management Automation and for Microsoft Azure Automation although the two will typically work with different resources.
Рабочие процессы Windows PowerShell Windows PowerShell Workflows
Рабочий процесс — это последовательность связанных программируемых операций, в ходе которых выполняются длительные задачи или скоординированные действия на нескольких устройствах или управляемых узлах. A workflow is a sequence of programmed, connected steps that perform long-running tasks or require the coordination of multiple steps across multiple devices or managed nodes. Преимущества рабочего процесса в сравнении с использованием обычного скрипта заключаются в возможности одновременного выполнения действия по отношению ко многим устройствам и в возможности автоматического восстановления при сбоях. The benefits of a workflow over a normal script include the ability to simultaneously perform an action against multiple devices and the ability to automatically recover from failures. Рабочий процесс Windows PowerShell представляет собой скрипт Windows PowerShell, который использует Windows Workflow Foundation. A Windows PowerShell Workflow is a Windows PowerShell script that leverages Windows Workflow Foundation. В то время как рабочий процесс прописан в синтаксисе Windows PowerShell и запускается Windows PowerShell, его обработка выполняется в Windows Workflow Foundation. While the workflow is written with Windows PowerShell syntax and launched by Windows PowerShell, it is processed by Windows Workflow Foundation.
Основная структура Basic Structure
Рабочий процесс Windows PowerShell начинается с ключевого слова рабочего процесса , за которым следует текст скрипта, заключенный в фигурные скобки. A Windows PowerShell Workflow starts with the Workflow keyword followed by the body of the script enclosed in braces. Имя рабочего процесса следует за ключевым словом Workflow , как это показано в следующем синтаксисе. The name of the workflow follows the Workflow keyword as shown in the following syntax. Имя рабочего процесса соответствует имени модуля Runbook службы автоматизации. The name of the workflow matches the name of the Automation runbook.
Чтобы добавить параметры в рабочий процесс, используйте ключевое слово param , как показано в следующем синтаксисе. To add parameters to the workflow, use the Param keyword as shown in the following syntax. Портал управления предложит пользователю предоставить значения этих параметров при запуске модуля runbook. The management Portal will prompt the user to provide values for these parameters when they start the runbook. В этом примере используется дополнительный атрибут Parameter, который указывает, обязателен ли этот параметр. This sample uses the optional Parameter attribute which specifies whether or not the parameter is mandatory.
Именование Naming
Имя рабочего процесса должно соответствовать формату «глагол-существительное», принятому в Windows PowerShell. The name of the workflow should conform to the Verb-Noun format that is standard with Windows PowerShell. Список утвержденных глаголов для использования можно найти в статье Approved Verbs for Windows PowerShell Commands (Утвержденные глаголы для команд Windows PowerShell) . You can refer to Approved Verbs for Windows PowerShell Commands for a list of approved verbs to use. Имя рабочего процесса должно соответствовать имени модуля Runbook в службе автоматизации. The name of the workflow must match the name of the Automation runbook. При импорте модуля Runbook имя файла должно соответствовать имени рабочего процесса и должно заканчиваться на .ps1. If the runbook is being imported, then the filename must match the workflow name and must end in .ps1.
Ограничения Limitations
Полный список ограничений и различий синтаксиса между Windows PowerShell и рабочими процессами Windows PowerShell см. в разделе Различия синтаксиса между сценариями и рабочими процессами сценариев. For a complete list of limitations and syntax differences between Windows PowerShell Workflows and Windows PowerShell, see Syntactic Differences Between Script Workflows and Scripts.
Действия Activities
Действие — это конкретная задача в рабочем процессе. An activity is a specific task in a workflow. Так же как скрипт состоит из одной или нескольких команд, рабочий процесс состоит из одного или нескольких действий, которые выполняются в последовательности. Just as a script is composed of one or more commands, a workflow is composed of one or more activities that are carried out in a sequence. Рабочий процесс Windows PowerShell автоматически преобразует множество командлетов Windows PowerShell в действия при выполнении рабочего процесса. Windows PowerShell Workflow automatically converts many of the Windows PowerShell cmdlets to activities when it runs a workflow. Если указать один из этих командлетов в модуле Runbook, соответствующее действие фактически запускается в Windows Workflow Foundation. When you specify one of these cmdlets in your runbook, the corresponding activity is actually run by Windows Workflow Foundation. Для командлетов, для которых не существует соответствующего действия, рабочий процесс Windows PowerShell автоматически запустит командлет в действии InlineScript. For those cmdlets without a corresponding activity, Windows PowerShell Workflow automatically runs the cmdlet within an InlineScript activity. Существует набор командлетов, которые исключены и не могут использоваться в рабочем процессе, если они явно не включены в блок InlineScript . There is a set of cmdlets that are excluded and cannot be used in a workflow unless you explicitly include them in an InlineScript block. Дополнительные сведения об этих понятиях см. в статье Использование действий в рабочих процессах сценариев. For further details on these concepts, see Using Activities in Script Workflows.
Действия рабочих процессов совместно используют набор общих параметров для настройки их работы. Workflow activities share a set of common parameters to configure their operation. Сведения об общих параметрах рабочего процесса см. в статье about_WorkflowCommonParameters. For details about the workflow common parameters, see about_WorkflowCommonParameters.
Модули интеграции Integration Modules
Модуль интеграции — это пакет, который содержит модуль Windows PowerShell и может быть импортирован в службу автоматизации. An Integration Module is a package that contains a Windows PowerShell Module and can be imported into Automation. Модули Windows PowerShell содержат командлеты, которые можно использовать в модулях Runbook службы автоматизации. Windows PowerShell Modules contain cmdlets that can be used in Automation runbooks. Продукты и службы, такие как Operations Manager и Azure, обладают модулями, содержащими командлеты для их работы. Products and services such as Operations Manager and Azure have modules that include cmdlets specific to their operation.
Модули интеграции, импортированные в службу автоматизации, автоматически доступны для всех модулей Runbook. Integration Modules that are imported into Automation are automatically available to all runbooks. Поскольку Автоматизация основана на Windows PowerShell 4,0, она поддерживает автоматическую загрузку модулей, что позволяет использовать командлеты из установленных модулей, не импортируя их в скрипт с параметром Import-Module. Since Automation is based on Windows PowerShell 4.0, it supports auto loading of modules meaning that cmdlets from installed modules can be used without importing them into the script with Import-Module.
Любой модуль Windows PowerShell можно импортировать в службу автоматизации при условии, что все его зависимости могут находиться в одной папке. Any Windows PowerShell module can be imported into Automation as long as all of its dependencies can be located in a single folder. Если модуль зависит от параметров реестра или файлов, не находящиеся в пути по умолчанию, он может быть импортирован, но, скорее всего, не будет работать, так как автоматизация не сможет располагать свои зависимости. If the module depends on registry settings or files not in the default path, then it can be imported, but it will most likely not work because Automation will not be able to locate its dependencies. Модули с внешними зависимостями могут быть использованы в модулях runbook путем установи их на другой узел и доступа к ним из блока сценария InlineScript . Modules with external dependencies can be used in a runbook by installing them on another host using and then accessing them with an InlineScript script block.
С помощью Service Management Automation можно использовать модули с внешними зависимостями, установив их на каждом рабочем сервере. With Service Management Automation, you can use modules with external dependencies by installing them on each Worker server. Хотя командлеты в этих модулях можно использовать в модулях Runbook, они не будут обнаружены службой автоматизации для поддержки таких функций, как мастер вставки действия. While the cmdlets in these modules can be used in runbooks, they will not be discovered by Automation to support such features as the Insert Activity wizard. Чтобы использовать этот компонент, можно создать переносимый модуль, используя командлет New-SmaPortableModule . In order to use this feature, you can create a Portable module using the New-SmaPortableModule cmdlet. Этот командлет создает модуль, который включает заглушку для каждого командлета и может быть импортирован в службу автоматизации. This cmdlet creates a module that includes a stub for each of its cmdlets and can be imported into Automation. Когда модуль Runbook использует один из этих командлетов, заглушка перенаправляет вызов в фактический командлет внешнего модуля. When a runbook uses one of those cmdlets, the stub redirects the call to the actual cmdlet in the external module. Этот модуль необходимо установить на каждом сервере Worker, в противном случае произойдет сбой вызова. That module must be installed on each Worker server or the call will fail.
Параллельное выполнение Parallel Execution
Одним из преимуществ рабочих процессов Windows PowerShell является возможность выполнять набор команд параллельно, а не последовательно, как это делается в стандартном скрипте. One advantage of Windows PowerShell Workflows is the ability to perform a set of commands in parallel instead of sequentially as with a typical script. Это особенно полезно в модулях Runbook, так как они могут выполнять несколько действий, требующих значительного времени. This is particularly useful in runbooks since they may perform multiple actions that take a significant time to complete. Например, модуль Runbook может выполнять подготовку группы виртуальных машин. For example, a runbook might provision a set of virtual machines. Вместо выполнения процедур подготовки последовательно действия могут выполняться одновременно, повышая общую эффективность. Rather than performing each provisioning process in sequence with one another, the actions could be performed simultaneously increasing overall efficiency. Модуль Runbook продолжит работу только после выполнения всех действий. Only when all are complete would the runbook continue.
Можно использовать ключевое слово Parallel , чтобы создать блок скрипта с несколькими командами, которые будут выполняться параллельно. You can use the Parallel keyword to create a script block with multiple commands that will run concurrently. Для этого используется приведенный ниже синтаксис. This uses the syntax shown below. В этом случае действия Activity1 и Activity2 будут запущены одновременно. In this case, Activity1 and Activity2 will start at the same time. Действие Activity3 запустится только после завершения действий Activity1 и Activity2. Activity3 will start only after both Activity1 and Activity2 have completed.
Можно использовать конструкцию ForEach -Parallel для обработки команд для каждого элемента в коллекции одновременно. You can use the ForEach -Parallel construct to process commands for each item in a collection concurrently. Элементы в коллекции обрабатываются параллельно, а команды в блоке скрипта выполняются последовательно. The items in the collection are processed in parallel while the commands in the script block run sequentially. Для этого используется приведенный ниже синтаксис. This uses the syntax shown below. В этом случае действие Activity1 будет запущено одновременно для всех элементов в коллекции. In this case, Activity1 will start at the same time for all items in the collection. Для каждого элемента действие Activity2 будет запускаться после завершения действия Activity1. For each item, Activity2 will start after Activity1 is complete. Действие Activity3 запустится только после завершения действий Activity1 и Activity2 для всех элементов. Activity3 will start only after both Activity1 and Activity2 have completed for all items.
Ключевое слово Sequence используется для выполнения команд в последовательности в блоке параллельного скрипта. The Sequence keyword is used to run commands in sequence within a Parallel script block. Блок сценария Sequence выполняется параллельно с другими командами, но команды внутри блока выполняются последовательно. The Sequence script block runs in parallel with other commands, but the commands within the block run sequentially. Для этого используется приведенный ниже синтаксис. This uses the syntax shown below. В этом случае действия Activity1, Activity2 и Activity3 будут запущены одновременно. In this case, Activity1, Activity2, and Activity3 will start at the same time. Действие Activity4 будет запускаться только после завершения действия Activity3. Activity4 will start only after Activity3 has completed. Действие Activity5 начнется после завершения всех действий. Activity5 will start after all other activities have completed
Контрольные точки Checkpoints
Контрольная точка представляет собой моментальный снимок текущего рабочего процесса, который включает текущие значения переменных и любые выходные данные, созданные для этой точки. A checkpoint is a snapshot of the current state of the workflow that includes the current value for variables and any output generated to that point. Последняя контрольная точка, которую необходимо выполнить в модуле Runbook, сохраняется в базе данных автоматизации, чтобы рабочий процесс можно было возобновить даже в случае сбоя. The last checkpoint to complete in a runbook is saved to the Automation database so that the workflow can resume even in the case of an outage. Данные контрольной точки удаляются после завершения задания модуля Runbook. The checkpoint data is removed once the runbook job is complete.
Можно установить контрольную точку для рабочего процесса при помощи действия Checkpoint-Workflow . You can set a checkpoint in a workflow with the Checkpoint-Workflow activity. При включении этого действия в модуль Runbook немедленно создается контрольная точка. When you include this activity in a runbook, a checkpoint is immediately taken. Если модуль Runbook приостанавливается из-за ошибки, при возобновлении задания оно возобновляется с момента последней заданной контрольной точки. If the runbook is suspended by an error, when the job is resumed, it will resume from the point of the last checkpoint set.
В следующем примере кода ошибка возникает после того как действие Activity2 вызывает приостановку модуля Runbook. In the following sample code, an error occurs after Activity2 causing the runbook to suspend. При возобновлении задания оно начинается с запуска Activity2, поскольку это действие было сразу после последней заданной контрольной точки. When the job is resumed, it starts by running Activity2 since this was just after the last checkpoint set.
Контрольные точки необходимо создавать в модуле Runbook после действий, которые подвержены ошибкам и не должны повторятся, когда возобновляется выполнение модуля. You should set checkpoints in a runbook after activities that may be prone to error and should not be repeated if the runbook is resumed. Например, модуль Runbook может создавать виртуальную машину. For example, your runbook may create a virtual machine. Контрольную точку следует создавать как до, так и после команды создания виртуальной машины. You could set a checkpoint both before and after the commands to create the virtual machine. В случае сбоя создания команды повторяются, когда возобновляется выполнение модуля Runbook. If the creation fails, then the commands are repeated when the runbook is resumed. Если создание выполняется успешно, но позднее происходит сбой выполнения Runbook, виртуальная машина не создается повторно при возобновлении Runbook. If the creation succeeds but the runbook later fails, then the virtual machine will not be created again when the runbook is resumed.
Дополнительные сведения о контрольных точках см. в статье Добавление контрольных точек в рабочий процесс сценария. For more information about checkpoints, see Adding Checkpoints to a Script Workflow.
Приостановка Runbook Suspend a Runbook
Вы можете принудительно приостановить модуль Runbook с помощью действия приостановки рабочего процесса . You can force a runbook to suspend itself with the Suspend-Workflow activity. Это действие задает контрольную точку и вызывает немедленную приостановку рабочего процесса. This activity will set a checkpoint and cause the workflow to immediately suspend. Приостановка рабочих процессов полезна для модулей runbook, в которых может потребоваться выполнение определенных задач вручную перед запуском следующего набора действий. Suspending a workflow is useful for runbooks that may require a manual step to be performed before another set of activities are run.
Дополнительные сведения о приостановке рабочего процесса см. в статье Making a Workflow Suspend Itself (Настройка приостановки рабочего процесса). For more information about suspending a workflow, see Making a Workflow Suspend Itself.
InlineScript (Встроенный сценарий) InlineScript
Действие InlineScript выполняет блок команд в отдельном сеансе, не являющемся рабочим процессом, и возвращает выходные данные в рабочий процесс. The InlineScript activity runs a block of commands in a separate, non-workflow session and returns its output to the workflow. Пока команды в рабочем процессе отправляются в Windows Workflow Foundation для обработки, команды в блоке InlineScript обрабатываются при помощи Windows PowerShell. While commands in a workflow are sent to Windows Workflow Foundation for processing, commands in an InlineScript block are processed by Windows PowerShell. Действие использует стандартные общие параметры рабочего процесса, включая PSComputerName и PSCredential , которые позволяют указать, что блок кода должен выполняться на другом компьютере или использовать альтернативные учетные данные. The activity uses the standard workflow common parameters including PSComputerName and PSCredential which allow you to specify that the code block be run on another computer or using alternate credentials.
InlineScript использует описанный ниже синтаксис. InlineScript uses the syntax shown below.
Наиболее распространенным использованием InlineScript в модуле Runbook является выполнение блока кода на другом компьютере. The most common use for InlineScript in a runbook is to run a block of code on another computer. Это необходимо, если командлеты в модуле Runbook не установлены в службе автоматизации или если действие имеет разрешения, которые должны быть выполнены локально на конечном компьютере. This is required when cmdlets in your runbook are not installed in Automation or if the action only has permissions to be performed locally on the target computer. Следующая диаграмма иллюстрирует эту схему. This is illustrated in the following diagram.
Для выполнения блока кода на другом компьютере параметры пскомпутер и PSCredential используются с действием InlineScript . In order to run the code block on another computer, the PSComputer and PSCredential parameters are used with the InlineScript activity. Для предоставления значений для этих параметров в модуле runbook обычно используется глобальный ресурс, например Credential или Connection . A global resource such as a Credential or Connection is typically used in a runbook to provide values for these parameters. Приведенный ниже пример кода демонстрирует запуск набора команд на компьютере, представленном подключением MyConnection. The following sample code runs a set of commands on a computer represented by a connection called MyConnection.
Хотя действия InlineScript могут быть критически важными в некоторых модулях Runbook, их следует использовать только при необходимости по следующим причинам. While InlineScript activities may be critical in certain runbooks, they should only be used when necessary for the following reasons:
Нельзя использовать контрольные точки в блоке InlineScript . You cannot use checkpoints from within an InlineScript block. Если в блоке происходит сбой, необходимо восстановить его выполнение с начала. If a failure occurs within the block, it must be resumed from the beginning.
InlineScript влияет на масштабируемость модуля Runbook, так как он содержит сеанс Windows PowerShell для всей длины блока InlineScript. InlineScript affects scalability of the runbook since it holds the Windows PowerShell session for the entire length of the InlineScript block.
Такие действия, как Get-AutomationVariable и Get-AutomationPSCredential , недоступны в блоке InlineScript. Activities such as Get-AutomationVariable and Get-AutomationPSCredential are not available in an InlineScript block.
Если необходимо использовать InlineScript, следует максимально ограничить его область. If you do need to use an InlineScript, you should minimize its scope. Например, если модуль Runbook выполняет итерацию по коллекции, одновременно применяя к каждому элементу ту же операцию, цикл должен происходить за пределами InlineScript. For example, if your runbook iterates over a collection while applying the same operation to each item, the loop should occur outside of the InlineScript. Это обеспечивает следующие преимущества. This will provide the following advantages:
Можно задать контрольную точку рабочего процесса после каждой итерации. You can checkpoint the workflow after each iteration. Если задание приостановлено или прервано, а затем возобновлено, цикл также будет возобновлен. If the job is suspended or interrupted and resumed, the loop will be able to resume.
Для параллельной обработки элементов коллекции можно использовать foreach «Parallel» . You can use ForEach «Parallel to handle collection items concurrently.
При использовании InlineScript в модуле Runbook учитывайте следующие рекомендации: Keep the following recommendations in mind if you do use an InlineScript in your runbook:
Можно передать значения в сценарий, используя модификатор области $Using . You can pass values into the script though with the $Using scope modifier. Например, переменная с именем $abc, которая была задана вне InlineScript, стала $using: ABC внутри InlineScript. For example, a variable called $abc that has been set outside of the InlineScript would become $using:abc inside an InlineScript.
Чтобы вернуть выходные данные из InlineScript, присвойте выходные данные переменной и выводит все возвращаемые в поток данных. To return output from an InlineScript, assign the output to a variable and output any data to be returned to the output stream. В следующем примере строка «Hi» присваивается переменной с именем $output. The following example assigns the string «hi» to a variable called $output.
Не следует определять рабочие процессы в области InlineScript . Avoid defining workflows within InlineScript scope. Некоторые рабочие процессы могут (внешне) работать правильно, но такой сценарий не тестировался. Even though some workflows may appear to operate correctly, this is not a tested scenario. Из-за этого возможны путаные сообщения об ошибках или непредвиденное поведение. As a result, you may encounter confusing error messages or unexpected behavior.
Дополнительные сведения об использовании InlineScript см. в разделе Выполнение команд Windows PowerShell в рабочем процессе и about_InlineScript. For further details on using InlineScript, see Running Windows PowerShell Commands in a Workflow and about_InlineScript.