Azure 自动化中的 Runbook 输出和消息Runbook output and messages in Azure Automation

大多数 Azure 自动化 runbook 都有某种形式的输出。Most Azure Automation runbooks have some form of output. 此输出可能是发给用户的错误消息,也可能是要用于另一个 Runbook 的复杂对象。This output can be an error message to the user or a complex object intended to be used with another runbook. Windows PowerShell 提供 多个流 ,以便从脚本或工作流发送输出。Windows PowerShell provides multiple streams to send output from a script or workflow. Azure 自动化以不同方式处理每个流。Azure Automation works with each of these streams differently. 在创建 Runbook 时,应遵循有关使用流的最佳做法。You should follow best practices for using the streams when you're creating a runbook.

下表简要描述了已发布 Runbook 以及在测试 Runbook 期间的每个流及其在 Azure 门户中的行为。The following table briefly describes each stream with its behavior in the Azure portal for published runbooks and during testing of a runbook. 输出流是用于 Runbook 之间的通信的主要流。The Output stream is the main stream used for communication between runbooks. 其他流分类为消息流,旨在将信息传达给用户。The other streams are classified as message streams, intended to communicate information to the user.

StreamStream 说明Description 已发布Published 测试Test
错误Error 面向用户的错误消息。Error message intended for the user. 与发生异常时不同,默认情况下,在出现错误消息后,Runbook 会继续执行。Unlike with an exception, the runbook continues after an error message by default. 写入作业历史记录Written to job history 显示在“测试”输出窗格中Displayed in Test output pane
调试Debug 面向交互式用户的消息。Messages intended for an interactive user. 不应在 Runbook 中使用。Shouldn't be used in runbooks. 不会写入作业历史记录Not written to job history 不会显示在“测试”输出窗格中Not displayed in Test output pane
输出Output 对象旨在由其他 Runbook 使用。Objects intended to be consumed by other runbooks. 写入作业历史记录Written to job history 显示在“测试”输出窗格中Displayed in Test output pane
进度Progress 完成 Runbook 中每个活动之前和之后自动生成的记录。Records automatically generated before and after each activity in the runbook. 由于 Runbook 面向交互式用户,因此不应尝试创建其自身的进度记录。The runbook shouldn't try to create its own progress records, since they're intended for an interactive user. 仅当为 Runbook 启用了进度日志记录时,才写入作业历史记录Written to job history only if progress logging is turned on for the runbook 不会显示在“测试”输出窗格中Not displayed in Test output pane
详细Verbose 提供一般信息或调试信息的消息。Messages that give general or debugging information. 仅当为 Runbook 启用了详细日志记录时,才写入作业历史记录Written to job history only if verbose logging is turned on for the runbook 仅当 Runbook 中的 VerbosePreference 变量设置为 Continue 时,才显示在“测试”输出窗格中Displayed in Test output pane only if VerbosePreference variable is set to Continue in runbook
警告Warning 面向用户的警告消息。Warning message intended for the user. 写入作业历史记录Written to job history 显示在“测试”输出窗格中Displayed in Test output pane


本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关适用于混合 Runbook 辅助角色的 Az 模块安装说明,请参阅安装 Azure PowerShell 模块For Az module installation instructions on your Hybrid Runbook Worker, see Install the Azure PowerShell Module.

输出流Output stream

输出流用于输出脚本或工作流创建的对象(如果该脚本或工作流正常运行)。The Output stream is used for the output of objects created by a script or workflow when it runs correctly. Azure 自动化主要将此流用于调用当前 Runbook 的父 Runbook 使用的对象。Azure Automation primarily uses this stream for objects to be consumed by parent runbooks that call the current runbook. 当父 Runbook 调用某个内联 Runbook 时,子级会将输出流中的数据返回给父级。When a parent calls a runbook inline, the child returns data from the Output stream to the parent.

仅在知道 Runbook 永不会被其他 Runbook 调用时,该 Runbook 才使用输出流将一般信息传达给客户端。Your runbook uses the Output stream to communicate general information to the client only if it is never called by another runbook. 但是,作为最佳做法,Runbook 通常应该使用详细流向用户传达一般信息。As a best practice, however, you runbooks should typically use the Verbose stream to communicate general information to the user.

让 Runbook 使用 Write-Output 向输出流写入数据。Have your runbook write data to the Output stream using Write-Output. 或者,可以在脚本中独行放置对象。Alternatively, you can put the object on its own line in the script.

#The following lines both write an object to the output stream.
Write-Output -InputObject $object

处理函数的输出Handling output from a function

当 Runbook 函数写入输出流时,输出将传回到 Runbook。When a runbook function writes to the Output stream, the output is passed back to the runbook. 如果 Runbook 将该输出分配给某个变量,则不会将输出写入输出流。If the runbook assigns that output to a variable, the output is not written to the output stream. 向函数内部的任何其他流写入数据会向 Runbook 的相应流写入数据。Writing to any other streams from within the function writes to the corresponding stream for the runbook. 请考虑以下示例 PowerShell 工作流 Runbook。Consider the following sample PowerShell Workflow runbook.

Workflow Test-Runbook
  Write-Verbose "Verbose outside of function" -Verbose
  Write-Output "Output outside of function"
  $functionOutput = Test-Function

  Function Test-Function
    Write-Verbose "Verbose inside of function" -Verbose
    Write-Output "Output inside of function"

Runbook 作业的输出流是:The Output stream for the runbook job is:

Output inside of function
Output outside of function

Runbook 作业的详细流是:The Verbose stream for the runbook job is:

Verbose outside of function
Verbose inside of function

发布 Runbook 之后、启动它之前,还必须在 Runbook 设置中启用详细日志记录,以获取详细流输出。Once you've published the runbook and before you start it, you must also turn on verbose logging in the runbook settings to get the Verbose stream output.

声明输出数据类型Declaring output data type

下面是输出数据类型的示例:The following are examples of output data types:

  • System.String
  • System.Int32
  • System.Collections.Hashtable
  • Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine

在工作流中声明输出数据类型Declare output data type in a workflow

工作流使用 OutputType 属性指定其输出的数据类型。A workflow specifies the data type of its output using the OutputType attribute. 此属性在运行时不起作用,但在设计时,它会指示 Runbook 的预期输出。This attribute has no effect during runtime, but it provides you an indication at design time of the expected output of the runbook. 随着 Runbook 工具集的持续发展,在设计时声明输出数据类型的重要性也在不断提升。As the tool set for runbooks continues to evolve, the importance of declaring output data types at design time increases. 因此,最佳做法是在创建的所有 Runbook 中包含此声明。Therefore it's a best practice to include this declaration in any runbooks that you create.

以下示例 Runbook 输出一个字符串对象,并包含其输出类型的声明。The following sample runbook outputs a string object and includes a declaration of its output type. 如果 Runbook 输出了特定类型的数组,则你仍应该指定相对于该类型数组的类型。If your runbook outputs an array of a certain type, then you should still specify the type as opposed to an array of the type.

Workflow Test-Runbook

  $output = "This is some string output."
  Write-Output $output

在图形 Runbook 中声明输出数据类型Declare output data type in a graphical runbook

若要在图形 Runbook 或图形 PowerShell 工作流 Runbook 中声明输出类型,可以选择“输入和输出”菜单选项,并输入输出类型。 To declare an output type in a graphical or graphical PowerShell Workflow runbook, you can select the Input and Output menu option and enter the output type. 建议使用完整的 .NET 类名,以便在父 Runbook 引用该类型时可以轻松识别它。It's recommended to use the full .NET class name to make the type easily identifiable when a parent runbook references it. 使用完整名称会向 Runbook 中的数据总线公开该类的所有属性,并在将这些属性用于条件逻辑、日志记录和作为其他 Runbook 活动的值引用时提高灵活性。Using the full name exposes all the properties of the class to the databus in the runbook and increases flexibility when the properties are used for conditional logic, logging, and referencing as values for other runbook activities.
Runbook 输入和输出选项Runbook Input and Output option


在“输入和输出属性”窗格中的“输出类型”字段内输入值后,请务必在控件外部单击,使控件识别输入内容。 After you enter a value in the Output Type field in the Input and Output properties pane, be sure to click outside the control so that it recognizes your entry.

以下示例中的两个图形 Runbook 演示了“输入和输出”功能。The following example shows two graphical runbooks to demonstrate the Input and Output feature. 如果应用模块式 Runbook 设计模型,则会获得一个“身份验证 Runbook”模板形式的 Runbook,用于管理使用运行方式帐户在 Azure 中进行的身份验证。Applying the modular runbook design model, you have one runbook as the Authenticate Runbook template managing authentication with Azure using the Run As account. 在本例中,通常执行核心逻辑来自动化给定方案的第二个 Runbook 将执行“身份验证 Runbook”模板。The second runbook, which normally performs core logic to automate a given scenario, in this case executes the Authenticate Runbook template. 它在“测试”输出窗格中显示结果。It displays the results to your Test output pane. 在正常情况下,会使用此 Runbook 针对利用子 Runbook 输出的资源执行某些操作。Under normal circumstances, you would have this runbook do something against a resource leveraging the output from the child runbook.

下面是 AuthenticateTo-Azure Runbook 的基本逻辑。Here is the basic logic of the AuthenticateTo-Azure runbook.
身份验证 Runbook 模板示例Authenticate Runbook Template Example.

该 Runbook 包括输出类型 Microsoft.Azure.Commands.Profile.Models.PSAzureContext,该类型返回身份验证配置文件属性。The runbook includes the output type Microsoft.Azure.Commands.Profile.Models.PSAzureContext, which returns the authentication profile properties.
Runbook 输出类型示例Runbook Output Type Example

尽管此 Runbook 操作非常简单,此处仍需调出一个配置项。While this runbook is straightforward, there is one configuration item to call out here. 最后一个活动执行 Write-Output cmdlet,以使用 Inputobject 参数的 PowerShell 表达式将配置文件数据写入某个变量。The last activity executes the Write-Output cmdlet to write profile data to a variable using a PowerShell expression for the Inputobject parameter. 此参数对于 Write-Output 是必需的。This parameter is required for Write-Output.

本示例中名为 Test-ChildOutputType 的第二个 Runbook 只是定义了两个活动。 The second runbook in this example, named Test-ChildOutputType, simply defines two activities.
示例子输出类型 RunbookExample Child Output Type Runbook

第一个活动调用 AuthenticateTo-Azure Runbook。 The first activity calls the AuthenticateTo-Azure runbook. 第二个活动在“数据源”设置为“活动输出”的情况下运行 Write-Verbose cmdlet。 The second activity runs the Write-Verbose cmdlet with Data source set to Activity output. 此外,“字段路径”设置为 Context.Subscription.SubscriptionName,即 AuthenticateTo-Azure Runbook 的上下文输出。 Also, Field path is set to Context.Subscription.SubscriptionName, the context output from the AuthenticateTo-Azure runbook.
Write-Verbose Cmdlet 参数数据源Write-Verbose Cmdlet Parameter Data Source

生成的输出是订阅名称。The resulting output is the name of the subscription.
Test-ChildOutputType Runbook 结果

消息流Message streams

与输出流不同,消息流向用户传达信息。Unlike the Output stream, message streams communicate information to the user. 有多个消息流用于传递不同类型的信息,Azure 自动化以不同的方式处理每个流。There are multiple message streams for different kinds of information, and Azure Automation handles each stream differently.

警告和错误流Warning and error streams

警告和错误流记录 Runbook 中出现的问题。The Warning and Error streams log problems that occur in a runbook. 执行 Runbook 时,Azure 自动化会将这些流写入作业历史记录。Azure Automation writes these streams to the job history when executing a runbook. 测试 Runbook 时,自动化会将这些流包含在 Azure 门户的“测试”输出窗格中。Automation includes the streams in the Test output pane in the Azure portal when a runbook is tested.

默认情况下,在出现警告或错误后,Runbook 将继续执行。By default, a runbook continues to execute after a warning or error. 在创建消息之前,可以通过让 Runbook 设置 preference 变量,指定 Runbook 应在出现警告或错误时暂停。You can specify that your runbook should suspend on a warning or error by having the runbook set a preference variable before creating the message. 例如,若要使 Runbook 在出现错误时暂停(就像发生异常时那样),请将 ErrorActionPreference 变量设置为 Stop。For example, to cause the runbook to suspend on an error as it does on an exception, set the ErrorActionPreference variable to Stop.

使用 Write-WarningWrite-Error cmdlet 创建警告或错误消息。Create a warning or error message using the Write-Warning or Write-Error cmdlet. 活动也可以写入到警告和错误流。Activities can also write to the Warning and Error streams.

#The following lines create a warning message and then an error message that will suspend the runbook.

$ErrorActionPreference = "Stop"
Write-Warning -Message "This is a warning message."
Write-Error -Message "This is an error message that will stop the runbook because of the preference variable."

调试流Debug stream

Azure 自动化对交互式用户使用调试消息流。Azure Automation uses the Debug message stream for interactive users. 不应在 Runbook 中使用此流。It should not be used in runbooks.

详细流Verbose stream

详细消息流支持有关 Runbook 操作的一般信息。The Verbose message stream supports general information about runbook operation. 由于调试流对 Runbook 不可用,因此,Runbook 应使用详细消息来传递调试信息。Since the Debug stream is not available for a runbook, your runbook should use verbose messages for debug information.

默认情况下,出于性能方面的原因,作业历史记录不会存储来自已发布 Runbook 的详细消息。By default, the job history does not store verbose messages from published runbooks, for performance reasons. 若要存储详细消息,请使用 Azure 门户上的“配置”选项卡中的“记录详细记录”设置将已发布的 Runbook 配置为记录详细消息。 To store verbose messages, use the Azure portal Configure tab with the Log Verbose Records setting to configure your published runbooks to log verbose messages. 启用此选项的目的只是为了排查 Runbook 的问题或对它进行调试。Turn on this option only to troubleshoot or debug a runbook. 在大多数情况下,应保留默认设置,即,不记录详细记录。In most cases, you should keep the default setting of not logging verbose records.

测试 runbook 时,即使已将该 runbook 配置为记录详细记录,详细消息也不会显示。When testing a runbook, verbose messages aren't displayed even if the runbook is configured to log verbose records. 若要在测试 Runbook 时显示详细消息,必须将 VerbosePreference 变量设置为 Continue。To display verbose messages while testing a runbook, you must set the VerbosePreference variable to Continue. 设置该变量后,Azure 门户的“测试”输出窗格中会显示详细消息。With that variable set, verbose messages are displayed in the Test output pane of the Azure portal.

以下代码使用 Write-Verbose cmdlet 创建详细消息。The following code creates a verbose message using the Write-Verbose cmdlet.

#The following line creates a verbose message.

Write-Verbose -Message "This is a verbose message."

进度记录Progress records

可以使用 Azure 门户的“配置”选项卡将 Runbook 配置为记录进度记录。 You can use the Configure tab of the Azure portal to configure a runbook to log progress records. 默认设置是不记录记录,以最大程度地提高性能。The default setting is to not log the records, to maximize performance. 在大多数情况下,应保留默认设置。In most cases, you should keep the default setting. 启用此选项的目的只是为了排查 Runbook 的问题或对它进行调试。Turn on this option only to troubleshoot or debug a runbook.

如果启用进度记录的记录,则每次运行活动之前和之后,Runbook 会在作业历史记录中写入一条记录。If you enable progress record logging, your runbook writes a record to job history before and after each activity runs. 测试 Runbook 不会显示进度消息,即使已将该 Runbook 配置为记录进度记录。Testing a runbook does not display progress messages even if the runbook is configured to log progress records.


Write-Progress cmdlet 在 runbook 中无效,因为此 cmdlet 旨在供交互式用户使用。The Write-Progress cmdlet is not valid in a runbook, since this cmdlet is intended for use with an interactive user.

Preference 变量Preference variables

可以在 Runbook 中设置某些 Windows PowerShell preference 变量,以控制对发送到不同输出流的数据做出的响应。You can set certain Windows PowerShell preference variables in your runbooks to control the response to data sent to different output streams. 下表列出了可在 Runbook 中使用的 preference 变量及其默认值和有效值。The following table lists the preference variables that can be used in runbooks, with their default and valid values. 在 Azure 自动化外部的 Windows PowerShell 中使用 preference 变量时,可对这些变量使用其他值。Additional values are available for the preference variables when used in Windows PowerShell outside of Azure Automation.

变量Variable 默认值Default Value 有效值Valid Values
WarningPreference 继续Continue 停止Stop
ErrorActionPreference 继续Continue 停止Stop
VerbosePreference SilentlyContinueSilentlyContinue StopStop

下表列出了在 Runbook 中有效的 preference 变量值的行为。The next table lists the behavior for the preference variable values that are valid in runbooks.

ValueValue 行为Behavior
继续Continue 记录消息并继续执行 Runbook。Logs the message and continues executing the runbook.
SilentlyContinueSilentlyContinue 继续执行 Runbook 但不记录消息。Continues executing the runbook without logging the message. 该值会导致忽略消息。This value has the effect of ignoring the message.
停止Stop 记录消息并挂起 Runbook。Logs the message and suspends the runbook.

检索 runbook 输出和消息Retrieving runbook output and messages

在 Azure 门户中检索 Runbook 输出和消息Retrieve runbook output and messages in Azure portal

可以在 Azure 门户中使用 Runbook 的“作业”选项卡查看 Runbook 作业的详细信息。 You can view the details of a runbook job in the Azure portal using the Jobs tab for the runbook. 作业摘要显示输入参数和输出流,此外,还显示有关作业的一般信息以及发生的任何异常。The job summary displays the input parameters and the Output stream, in addition to general information about the job and any exceptions that have occurred. 作业历史记录包含来自输出流以及警告和错误流的消息。The job history includes messages from the Output stream and Warning and Error streams. 此外,如果 Runbook 配置为记录详细记录和进度记录,则作业历史记录还包含来自详细流进度记录的消息。It also includes messages from the Verbose stream and progress records if the runbook is configured to log verbose and progress records.

在 Windows PowerShell 中检索 Runbook 输出和消息Retrieve runbook output and messages in Windows PowerShell

在 Windows PowerShell 中,可以使用 Get-AzureAutomationJobOutput cmdlet 检索 Runbook 的输出和消息。In Windows PowerShell, you can retrieve output and messages from a runbook using the Get-AzureAutomationJobOutput cmdlet. 此 cmdlet 需要作业的 ID,并具有一个名为 Stream 的参数,在其中可以指定要检索的流。This cmdlet requires the ID of the job and has a parameter called Stream in which to specify the stream to retrieve. 可为此参数指定 Any 值,以检索作业的所有流。You can specify a value of Any for this parameter to retrieve all streams for the job.

以下示例将启动一个示例 Runbook,并等待该 Runbook 完成。The following example starts a sample runbook and then waits for it to complete. Runbook 执行完成后,脚本将从作业收集 Runbook 输出流。Once the runbook completes execution, the script collects the runbook output stream from the job.

$job = Start-AzAutomationRunbook -ResourceGroupName "ResourceGroup01" `
  -AutomationAccountName "MyAutomationAccount" -Name "Test-Runbook"

$doLoop = $true
While ($doLoop) {
  $job = Get-AzAutomationJob -ResourceGroupName "ResourceGroup01" `
    -AutomationAccountName "MyAutomationAccount" -Id $job.JobId
  $status = $job.Status
  $doLoop = (($status -ne "Completed") -and ($status -ne "Failed") -and ($status -ne "Suspended") -and ($status -ne "Stopped"))

Get-AzAutomationJobOutput -ResourceGroupName "ResourceGroup01" `
  -AutomationAccountName "MyAutomationAccount" -Id $job.JobId -Stream Output

# For more detailed job output, pipe the output of Get-AzAutomationJobOutput to Get-AzAutomationJobOutputRecord
Get-AzAutomationJobOutput -ResourceGroupName "ResourceGroup01" `
  -AutomationAccountName "MyAutomationAccount" -Id $job.JobId -Stream Any | Get-AzAutomationJobOutputRecord

检索图形 Runbook 中的 Runbook 输出和消息Retrieve runbook output and messages in graphical runbooks

对于图形 Runbook,可通过活动级跟踪的形式额外记录输出和消息。For graphical runbooks, extra logging of output and messages is available in the form of activity-level tracing. 有两个级别的跟踪:基本和详细。There are two levels of tracing: Basic and Detailed. 基本跟踪显示 Runbook 中每个活动的开始和结束时间,以及与任何活动重试相关的信息。Basic tracing displays the start and end time for each activity in the runbook, plus information related to any activity retries. 例如,活动的尝试次数和开始时间。Some examples are the number of attempts and the start time of the activity. 详细跟踪包含基本跟踪功能,此外会记录每个活动的输入和输出数据。Detailed tracing includes basic tracing features plus logging of input and output data for each activity.

目前,活动级跟踪将使用详细流写入记录。Currently activity-level tracing writes records using the Verbose stream. 因此,在启用跟踪时,必须启用详细日志记录。Therefore you must enable verbose logging when you enable tracing. 对于启用了跟踪的图形 runbook,无需记录进度记录。For graphical runbooks with tracing enabled, there's no need to log progress records. 基本跟踪起着相同的目的,并且提供更多信息。Basic tracing serves the same purpose and is more informative.


从插图中可以看出,为图形 Runbook 启用详细日志记录和跟踪会在生产“作业流”视图中产生多得多的信息。 You can see from the image that enabling verbose logging and tracing for graphical runbooks makes much more information available in the production Job Streams view. 这些额外的信息对于排查 Runbook 的生产问题至关重要。This extra information can be essential for troubleshooting production problems with a runbook.

但是,除非需要此信息来跟踪 Runbook 进度以进行故障排除,否则一般情况下,建议将跟踪保持禁用状态。However, unless you require this information to track the progress of a runbook for troubleshooting, you might want to keep tracing turned off as a general practice. 跟踪记录可能特别庞大。The trace records can be especially numerous. 使用图形 Runbook 跟踪时,可以获取每个活动的二到四条记录,具体取决于是配置了基本跟踪还是详细跟踪。With graphical runbook tracing, you can get two to four records per activity, depending on your configuration of Basic or Detailed tracing.

若要启用活动级跟踪:To enable activity-level tracing:

  1. 在 Azure 门户中,打开自动化帐户。In the Azure portal, open your Automation account.

  2. 在“过程自动化”下选择“Runbook”,打开 Runbook 列表。 Select Runbooks under Process Automation to open the list of runbooks.

  3. 在“Runbook”页上,从 Runbook 列表中选择一个图形 Runbook。On the Runbooks page, select a graphical runbook from your list of runbooks.

  4. 在“设置” 下,单击“日志记录和跟踪” 。Under Settings, click Logging and tracing.

  5. 在“日志记录和跟踪”页上的“记录详细记录”下,单击“打开”以启用详细日志记录。 On the Logging and Tracing page, under Log verbose records, click On to enable verbose logging.

  6. 在“活动级跟踪”下,根据所需的跟踪级别,将跟踪级别更改为“基本”或“详细”。 Under Activity-level tracing, change the trace level to Basic or Detailed, based on the level of tracing you require.


在 Azure Monitor 日志中检索 Runbook 输出和消息Retrieve runbook output and messages in Azure Monitor logs

Azure 自动化可将 Runbook 作业状态和作业流发送到 Log Analytics 工作区。Azure Automation can send runbook job status and job streams to your Log Analytics workspace. Azure Monitor 支持使用日志来实现以下目的:Azure Monitor supports logs that allow you to:

  • 获取有关自动化作业的见解。Get insight on your Automation jobs.
  • 基于 Runbook 作业状态(例如“失败”或“暂停”)触发电子邮件或警报。Trigger an email or alert based on your runbook job status, for example, Failed or Suspended.
  • 针对不同的作业流编写高级查询。Write advanced queries across job streams.
  • 跨自动化帐户关联作业。Correlate jobs across Automation accounts.
  • 可视化作业历史记录。Visualize job history.

有关如何配置与 Azure Monitor 日志的集成以收集、关联和处理作业数据的详细信息,请参阅将作业状态和作业流从自动化转发到 Azure Monitor 日志For more information on configuring integration with Azure Monitor logs to collect, correlate, and act on job data, see Forward job status and job streams from Automation to Azure Monitor logs.

后续步骤Next steps