在 Azure 自动化中执行 RunbookRunbook execution in Azure Automation

Runbook 基于其内部定义的逻辑执行。Runbooks execute based on the logic defined inside them. 如果 Runbook 中断,则 Runbook 将在开始时重启。If a runbook is interrupted, the runbook restarts at the beginning. 这种行为要求编写的 Runbook 在发生暂时性问题时支持重启。This behavior requires you to write runbooks that support being restarted if transient issues occur.

在 Azure 自动化中启动 Runbook 会创建一个作业。Starting a runbook in Azure Automation creates a job. 作业是 Runbook 的单一执行实例。A job is a single execution instance of the runbook. 每个作业可以通过与 Azure 订阅建立连接来访问 Azure 资源。Each job has access to Azure resources by making a connection to your Azure subscription. 仅当数据中心内的资源可从云访问时,作业才能访问这些资源。The job only has access to resources in your datacenter if those resources are accessible from the cloud.

在执行 Runbook 期间,Azure 自动化将分配一个辅助角色来运行每个作业。Azure Automation assigns a worker to run each job during runbook execution. 尽管辅助角色由多个 Azure 帐户共享,但不同自动化帐户中的作业是相互独立的。While workers are shared by many Azure accounts, jobs from different Automation accounts are isolated from one another. 无法控制要由哪个辅助角色为作业请求提供服务。You don't have control over which worker services your job request.

在 Azure 门户中查看 Runbook 列表时,会显示针对每个 Runbook 启动的作业的状态。When you view the list of runbooks in the Azure portal, it shows the status of each job that has been started for each runbook. Azure 自动化将作业日志最多存储 30 天。Azure Automation stores job logs for a maximum of 30 days.

下图显示 PowerShell Runbook图形 RunbookPowerShell 工作流 Runbook 的 Runbook 作业生命周期。The following diagram shows the lifecycle of a runbook job for PowerShell runbooks, Graphical runbooks, and PowerShell Workflow runbooks.

作业状态 - PowerShell 工作流

备注

如果有兴趣查看或删除个人数据,请参阅 GDPR 的 Azure 数据使用者请求一文。If you’re interested in viewing or deleting personal data, please see the Azure Data Subject Requests for the GDPR article. 如需关于 GDPR 的常规信息,请参阅服务信任门户的 GDPR 部分If you’re looking for general info about GDPR, see the GDPR section of the Service Trust portal.

运行 runbook 的位置Where to run your runbooks

Azure 自动化中的 Runbook 可以在 Azure 沙盒上运行,也可以在混合 Runbook 辅助角色上运行。Runbooks in Azure Automation can run on either an Azure sandbox or a Hybrid Runbook Worker. 大多数 Runbook 可以轻松在 Azure 沙盒中运行。沙盒是多个作业可以使用的共享环境。Most runbooks can easily be run in an Azure sandbox, a shared environment that multiple jobs can use. 使用同一沙盒的作业受沙盒的资源限制约束。Jobs using the same sandbox are bound by the resource limitations of the sandbox.

使用混合 Runbook 辅助角色既可以直接在托管角色的计算机上运行 Runbook,也可以对环境中的本地资源运行 Runbook。You can use a Hybrid Runbook Worker to run runbooks directly on the computer that hosts the role and against local resources in the environment. Azure 自动化将存储并管理 Runbook,然后将其传送到一台或多台指定的计算机。Azure Automation stores and manages runbooks and then delivers them to one or more assigned computers.

下表列出了一些 Runbook 执行任务,以及每个任务的建议执行环境。The following table lists some runbook execution tasks with the recommended execution environment listed for each.

任务Task 最佳选择Best Choice 注释Notes
与 Azure 资源集成Integrate with Azure resources Azure 沙盒Azure Sandbox 托管在 Azure 中,身份验证更为简单。Hosted in Azure, authentication is simpler. 如果使用的是 Azure VM 上的混合 Runbook 辅助角色,则可使用 Azure 资源的托管标识If you are using a Hybrid Runbook Worker on an Azure VM, you can use managed identities for Azure resources.
管理 Azure 资源时可以获得最佳性能Obtain optimal performance to manage Azure resources Azure 沙盒Azure Sandbox 脚本在同一环境中运行,因此延迟更低。Script is run in the same environment, which has less latency.
最大程度减少运营成本Minimize operational costs Azure 沙盒Azure Sandbox 没有计算开销,不需要 VM。There is no compute overhead and no need for a VM.
执行长时间运行的脚本Execute long-running script 混合 Runbook 辅助角色Hybrid Runbook Worker Azure 沙盒对资源施加限制Azure sandboxes have limitations on resources.
与本地服务交互Interact with Local Services 混合 Runbook 辅助角色Hybrid Runbook Worker 可以直接访问主机。Can have access directly to host machine.
需要第三方软件和可执行文件Require third-party software and executables 混合 Runbook 辅助角色Hybrid Runbook Worker 由你管理操作系统,可以安装软件。You manage the operating system and can install software.
运行资源密集型脚本Run a resource-intensive script 混合 Runbook 辅助角色Hybrid Runbook Worker Azure 沙盒对资源施加限制Azure sandboxes have limitations on resources.
使用存在特定要求的模块Use modules with specific requirements 混合 Runbook 辅助角色Hybrid Runbook Worker 下面是一些示例:Some examples are:
WinSCP - winscp.exe 上的依赖项WinSCP - dependency on winscp.exe
IISAdministration - 依赖于启用 IIS。IISAdministration - dependency on enabling of IIS.
使用安装程序安装模块Install a module with an installer 混合 Runbook 辅助角色Hybrid Runbook Worker 沙盒的模块必须支持复制。Modules for sandbox must support copying.
使用需要不同于 4.7.2 版本的 .NET Framework 的 Runbook 或模块Use runbooks or modules that require .NET Framework version different from 4.7.2 混合 Runbook 辅助角色Hybrid Runbook Worker 自动化沙盒使用 .NET Framework 4.7.2,无法升级 .NET Framework。Automation sandboxes have .NET Framework 4.7.2, and there is no way to upgrade it.
运行需要提升权限的脚本Run scripts that require elevation 混合 Runbook 辅助角色Hybrid Runbook Worker 沙盒不允许提升权限。Sandboxes do not allow elevation. 使用混合 Runbook 辅助角色可以关闭 UAC,并在运行需要提升权限的命令时使用 Invoke-CommandWith a Hybrid Runbook Worker, you can turn off UAC and use Invoke-Command when running the command that requires elevation.
运行需要访问 WMI 的脚本Run scripts that require access to WMI 混合 Runbook 辅助角色Hybrid Runbook Worker 在云中的沙盒中运行的作业无权访问 WMI。Jobs running in sandboxes in the cloud do not have access to WMI.

Runbook 行为Runbook behavior

创建资源Creating resources

如果 Runbook 要创建某个资源,在尝试创建该资源之前,脚本应检查该资源是否已存在。If your runbook creates a resource, the script should check to see if the resource already exists before attempting to create it. 下面是一个基本示例。Here's a basic example.

$vmName = "WindowsVM1"
$resourceGroupName = "myResourceGroup"
$myCred = Get-AutomationPSCredential "MyCredential"
$vmExists = Get-AzureRmResource -Name $vmName -ResourceGroupName $resourceGroupName

if(!$vmExists)
    {
    Write-Output "VM $vmName does not exist, creating"
    New-AzureRMVM -Name $vmName -ResourceGroupName $resourceGroupName -Credential $myCred
    }
else
    {
    Write-Output "VM $vmName already exists, skipping"
    }

支持时间依赖脚本Supporting time-dependent scripts

Runbook 必须可靠,且能够处理可能导致它们重启或失败的暂时性错误。Your runbooks must be robust and capable of handling transient errors that can cause them to restart or fail. 如果 Runbook 失败,Azure 自动化会重试该 Runbook。If a runbook fails, Azure Automation retries it.

如果 Runbook 在时间约束范围内正常运行,请在脚本中实现检查执行时间的逻辑。If your runbook normally runs within a time constraint, have the script implement logic to check the execution time. 此项检查可确保只在特定时间运行启动、关闭或横向扩展等操作。This check ensures the running of operations such as startup, shutdown, or scale-out only during specific times.

备注

Azure 沙盒进程上的本地时间设置为 UTC 时间。The local time on the Azure sandbox process is set to UTC. Runbook 中的日期和时间计算需要考虑到这一点。Calculations for date and time in your runbooks must take this fact into consideration.

跟踪进度Tracking progress

合理的做法是创作模块性的 Runbook,并构建 Runbook 逻辑,以便能够轻松重用和重启 Runbook。It is a good practice to author your runbooks to be modular in nature, structuring runbook logic so that it can be reused and restarted easily. 跟踪 Runbook 的进度能够很好地确保在出现问题时正常执行 Runbook 逻辑。Tracking progress in a runbook is a good way to ensure that the runbook logic executes correctly if there are issues. 可以使用存储帐户、数据库或共享文件等外部源跟踪 Runbook 的进度。It's possible to track the progress of a runbook by using an external source, such as a storage account, a database, or shared files. 可以在 Runbook 中创建逻辑,以便先检查所执行的最后一个操作的状态。You can create logic in your runbook to first check the state of the last action taken. 然后,该逻辑可以根据检查结果跳过或继续执行 Runbook 中的特定任务。Then, based on the result of the check, the logic can either skip or continue specific tasks in the runbook.

防止并发作业Preventing concurrent jobs

某些 Runbook 在同时针对多个作业运行时会出现怪异的行为。Some runbooks behave strangely if they run across multiple jobs at the same time. 在此情况下,必须让 Runbook 实现相应的逻辑来确定是否已存在运行中的作业。In this case, it's important for a runbook to implement logic to determine if there is already a running job. 下面是一个基本示例。Here's a basic example.

# Authenticate to Azure
$connection = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzureRmAccount -EnvironmentName AzureChinaCloud -ServicePrincipal -Tenant $connection.TenantID `
-ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint

$AzureContext = Select-AzureRmSubscription -SubscriptionId $connection.SubscriptionID

# Check for already running or new runbooks
$runbookName = "<RunbookName>"
$rgName = "<ResourceGroupName>"
$aaName = "<AutomationAccountName>"
$jobs = Get-AzureRmAutomationJob -ResourceGroupName $rgName -AutomationAccountName $aaName -RunbookName $runbookName -AzureRmContext $AzureContext

# Check to see if it is already running
$runningCount = ($jobs | ? {$_.Status -eq "Running"}).count

If (($jobs.status -contains "Running" -And $runningCount -gt 1 ) -Or ($jobs.Status -eq "New")) {
    # Exit code
    Write-Output "Runbook is already running"
    Exit 1
} else {
    # Insert Your code here
}

使用多个订阅Working with multiple subscriptions

若要处理多个订阅,Runbook 必须使用 Disable-AzureRmContextAutosave cmdlet 来确保不会从同一个沙盒中运行的另一个 Runbook 检索到身份验证上下文。To deal with multiple subscriptions, your runbook must use the Disable-AzureRmContextAutosave cmdlet to ensure that the authentication context is not retrieved from another runbook running in the same sandbox. Runbook 还会在 AzureRM cmdlet 中使用 -AzureRmContext 参数,并将其传递给适当的上下文。The runbook also uses the -AzureRmContext parameter on the AzureRM cmdlets and passes it the proper context.

# Ensures that you do not inherit an AzureRMContext in your runbook
Disable-AzureRmContextAutosave -Scope Process

$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzureRmAccount -ServicePrincipal `
-EnvironmentName AzureChinaCloud `
-Tenant $Conn.TenantID `
-ApplicationId $Conn.ApplicationID `
-CertificateThumbprint $Conn.CertificateThumbprint

$context = Get-AzureRmContext

$ChildRunbookName = 'ChildRunbookDemo'
$AutomationAccountName = 'myAutomationAccount'
$ResourceGroupName = 'myResourceGroup'

Start-AzureRmAutomationRunbook `
    -ResourceGroupName $ResourceGroupName `
    -AutomationAccountName $AutomationAccountName `
    -Name $ChildRunbookName `
    -DefaultProfile $context

处理异常Handling exceptions

本部分介绍如何在 Runbook 中处理异常或间歇性问题。This section describes some ways to handle exceptions or intermittent issues in your runbooks.

$ErrorActionPreference$ErrorActionPreference

$ErrorActionPreference 变量确定 PowerShell 如何对非终止性错误做出响应。The $ErrorActionPreference variable determines how PowerShell responds to a non-terminating error. 终止性错误始终会终止,不受 $ErrorActionPreference 的影响。Terminating errors always terminate and are not affected by $ErrorActionPreference.

当 Runbook 使用 $ErrorActionPreference 时,正常的非终止性错误(例如 Get-ChildItem cmdlet 返回的 PathNotFound)会阻止 Runbook 完成。When the runbook uses $ErrorActionPreference, a normally non-terminating error such as PathNotFound from the Get-ChildItem cmdlet stops the runbook from completing. 以下示例演示 $ErrorActionPreference 的用法。The following example shows the use of $ErrorActionPreference. 由于脚本将会停止,最终的 Write-Output 命令永远不会执行。The final Write-Output command never executes, as the script stops.

$ErrorActionPreference = 'Stop'
Get-Childitem -path nofile.txt
Write-Output "This message will not show"

Try Catch FinallyTry Catch Finally

在 PowerShell 脚本中使用 Try Catch Finally 可以处理终止性错误。Try Catch Finally is used in PowerShell scripts to handle terminating errors. 脚本可以使用此机制捕获特定的异常或一般的异常。The script can use this mechanism to catch specific exceptions or general exceptions. 应使用 catch 语句来跟踪错误或尝试处理错误。The catch statement should be used to track or try to handle errors. 以下示例尝试下载一个不存在的文件。The following example tries to download a file that does not exist. 它捕获 System.Net.WebException 异常,并返回任何其他异常的最后一个值。It catches the System.Net.WebException exception and returns the last value for any other exception.

try
{
   $wc = new-object System.Net.WebClient
   $wc.DownloadFile("http://www.contoso.com/MyDoc.doc")
}
catch [System.Net.WebException]
{
    "Unable to download MyDoc.doc from http://www.contoso.com."
}
catch
{
    "An error occurred that could not be resolved."
}

ThrowThrow

可以使用 Throw 来生成终止性错误。Throw can be used to generate a terminating error. 在 Runbook 中定义自己的逻辑时,此机制可能非常有用。This mechanism can be useful when defining your own logic in a runbook. 如果脚本满足特定的停止条件,则它可以使用 throw 语句停止。If the script meets a criterion that should stop it, it can use the throw statement to stop. 以下示例使用此语句显示所需的函数参数。The following example uses this statement to show a required function parameter.

function Get-ContosoFiles
{
  param ($path = $(throw "The Path parameter is required."))
  Get-ChildItem -Path $path\*.txt -recurse
}

使用可执行文件或调用进程Using executables or calling processes

在 Azure 沙盒中运行的 Runbook 不支持调用进程,例如可执行文件( .exe 文件)或子进程。Runbooks that run in Azure sandboxes do not support calling processes, such as executables (.exe files) or subprocesses. 这是因为,Azure 沙盒是在容器中运行的共享进程,它可能无权访问所有底层 API。The reason for this is that an Azure sandbox is a shared process run in a container that might not have access to all the underlying APIs. 对于需要第三方软件或调用子进程的方案,建议在混合 Runbook 辅助角色上执行 Runbook。For scenarios requiring third-party software or calls to subprocesses, it is recommended to execute a runbook on a Hybrid Runbook Worker.

访问设备和应用程序特征Accessing device and application characteristics

在 Azure 沙盒中运行的 Runbook 作业无权访问任何设备或应用程序特征。Runbook jobs that run in Azure sandboxes don't have access to any device or application characteristics. 最常用于在 Windows 上查询性能指标的 API 是 WMI,其中的一些常见指标是内存和 CPU 使用率。The most common API used to query performance metrics on Windows is WMI, with some of the common metrics being memory and CPU usage. 但是,使用哪个 API 并不重要,因为在云中运行的作业无权访问基于 Web 的企业管理 (WBEM) 的 Azure 实现。However, it doesn't matter what API is used, as jobs running in the cloud don't have access to the Azure implementation of Web-Based Enterprise Management (WBEM). 此平台构建在通用信息模型 (CIM) 的基础之上。CIM 提供有关定义设备和应用程序特征的行业标准。This platform is built on the Common Information Model (CIM), providing the industry standards for defining device and application characteristics.

处理错误Handling errors

Runbook 必须能够处理错误。Your runbooks must be capable of handling errors. PowerShell 具有两种类型的错误:终止性和非终止性。PowerShell has two types of errors, terminating and non-terminating. 发生终止性错误时,Runbook 会停止执行。Terminating errors stop runbook execution when they occur. Runbook 将会停止,作业状态为“失败”。 The runbook stops with a job status of Failed.

即使发生非终止性错误,脚本也能继续运行。Non-terminating errors allow a script to continue even after they occur. 例如,当 Runbook 对某个不存在的路径使用 Get-ChildItem cmdlet 时,就会发生非终止错误。An example of a non-terminating error is one that occurs when a runbook uses the Get-ChildItem cmdlet with a path that doesn't exist. PowerShell 发现路径不存在,然后引发错误,并继续转到下一文件夹。PowerShell sees that the path doesn't exist, throws an error, and continues to the next folder. 在此情况下,该错误不会将 Runbook 作业状态设置为“失败”,甚至可能会完成作业。 The error in this case doesn't set runbook job status status to Failed, and the job might even be completed. 若要强制 runbook 在发生非终止性错误时停止,可以使用 -ErrorAction Stop cmdlet。To force a runbook to stop on a non-terminating error, you can use -ErrorAction Stop on the cmdlet.

处理作业Handling jobs

可以重用同一自动化帐户中的作业的执行环境。You can reuse the execution environment for jobs from the same Automation account. 一个 runbook 可以同时运行多个作业。A single runbook can have many jobs running at one time. 同时运行的作业越多,就越可能将其分派到同一个沙盒中。The more jobs you run at the same time, the more often they can be dispatched to the same sandbox.

在同一沙盒进程中运行的作业可能会相互影响。Jobs running in the same sandbox process can affect each other. 一个示例就是运行 Disconnect-AzureRmAccount cmdlet。One example is running the Disconnect-AzureRmAccount cmdlet. 执行此 cmdlet 会断开共享沙盒进程中的每个 Runbook 作业。Execution of this cmdlet disconnects each runbook job in the shared sandbox process.

从 Azure 沙盒中运行的 Runbook 启动的 PowerShell 作业在完整语言模式下可能无法运行。PowerShell jobs started from a runbook that runs in an Azure sandbox might not run in the full language mode. 若要了解有关 PowerShell 语言模式的详细信息,请参阅 PowerShell 语言模式To learn more about PowerShell language modes, see PowerShell language modes. 有关如何与 Azure 自动化中的作业进行交互的更多详细信息,请参阅使用 PowerShell 检索作业状态For additional details on interacting with jobs in Azure Automation, see Retrieving job status with PowerShell.

作业状态Job statuses

下表描述了作业的可能状态。The following table describes the statuses that are possible for a job.

状态Status 说明Description
已完成Completed 作业已成功完成。The job completed successfully.
已失败Failed 图形 Runbook 或 PowerShell 工作流 Runbook 无法编译。A graphical or PowerShell Workflow runbook failed to compile. PowerShell 脚本 Runbook 无法启动,或作业出现异常。A PowerShell script runbook failed to start or the job had an exception. 请参阅 Azure 自动化 Runbook 类型See Azure Automation runbook types.
失败,正在等待资源Failed, waiting for resources 作业失败,因为它已达到 公平份额 限制三次,并且每次都已从同一个检查点或 Runbook 开始处启动。The job failed because it reached the fair share limit three times and started from the same checkpoint or from the start of the runbook each time.
已排队Queued 作业正在等待提供自动化工作线程的资源,以便能够启动。The job is waiting for resources on an Automation worker to become available so that it can be started.
正在启动Starting 作业已分配给辅助角色,并且系统正在将它启动。The job has been assigned to a worker, and the system is starting it.
正在恢复Resuming 系统正在恢复已暂停的作业。The system is resuming the job after it was suspended.
正在运行Running 作业正在运行。The job is running.
正在运行,正在等待资源Running, waiting for resources 作业已卸载,因为它已达到公平份额限制。The job has been unloaded because it reached the fair share limit. 片刻之后,它会从其上一个检查点恢复。It will resume shortly from its last checkpoint.
已停止Stopped 作业在完成之前已被用户停止。The job was stopped by the user before it was completed.
正在停止Stopping 系统正在停止作业。The system is stopping the job.
已挂起Suspended 仅适用于图形 Runbook 和 PowerShell 工作流 RunbookApplies to graphical and PowerShell Workflow runbooks only. 作业已被用户、系统或 Runbook 中的命令暂停。The job was suspended by the user, by the system, or by a command in the runbook. 如果 Runbook 没有检查点,它将从头开始启动。If a runbook doesn't have a checkpoint, it starts from the beginning. 如果它有检查点,它将重新启动并从其上一个检查点继续。If it has a checkpoint, it can start again and resume from its last checkpoint. 仅当发生异常时,系统才会挂起 Runbook。The system only suspends the runbook when an exception occurs. 默认情况下,ErrorActionPreference 变量设置为 Continue,表示出错时作业会保持运行。By default, the ErrorActionPreference variable is set to Continue, indicating that the job keeps running on an error. 如果该首选项变量设置为 Stop,则出错时作业会挂起。If the preference variable is set to Stop, the job suspends on an error.
正在暂停Suspending 仅适用于图形 Runbook 和 PowerShell 工作流 RunbookApplies to graphical and PowerShell Workflow runbooks only. 系统正在尝试按用户请求暂停作业。The system is trying to suspend the job at the request of the user. Runbook 只有在达到其下一个检查点后才能挂起。The runbook must reach its next checkpoint before it can be suspended. 如果 Runbook 越过了最后一个检查点,则只有在完成后才能挂起。If it has already passed its last checkpoint, it completes before it can be suspended.

从 Azure 门户查看作业状态Viewing job status from the Azure portal

可以查看所有 runbook 作业的概述状态或在 Azure 门户中深入了解特定 runbook 作业的详细信息。You can view a summarized status of all runbook jobs or drill into details of a specific runbook job in the Azure portal. 此外,还可配置与 Log Analytics 工作区的集成,以转发 runbook 作业状态和作业流。You can also configure integration with your Log Analytics workspace to forward runbook job status and job streams. 有关与 Azure Monitor 日志集成的详细信息,请参阅将作业状态和作业流从自动化转发到 Azure Monitor 日志For more information about integrating with Azure Monitor logs, see Forward job status and job streams from Automation to Azure Monitor logs.

在所选自动化帐户的右侧,可在“作业统计信息”磁贴下看到所有 Runbook 作业的摘要。 On the right of your selected Automation account, you can see a summary of all the runbook jobs under the Job Statistics tile.

作业统计信息磁贴

此磁贴显示执行的每个作业的计数及其状态的图形表示形式。This tile displays a count and graphical representation of the job status for each job executed.

单击磁贴可显示“作业”页,此页包括所有已执行作业的摘要列表 。Clicking the tile presents the Jobs page, which includes a summarized list of all jobs executed. 此页显示每个作业的状态、Runbook 名称、开始时间和完成时间。This page shows the status, runbook name, start time, and completion time for each job.

自动化帐户作业页

可以选择“筛选作业”来筛选作业列表。 You can filter the list of jobs by selecting Filter jobs. 可按特定的 Runbook 和作业状态进行筛选,或者从下拉列表中进行选择,并提供搜索时间范围。Filter on a specific runbook, job status, or a choice from the dropdown list, and provide the time range for the search.

筛选作业状态

或者,可通过从自动化帐户中的“Runbook”页上选择特定的 Runbook,并选择“作业”磁贴,来查看该 Runbook 的作业摘要详细信息。 Alternatively, you can view job summary details for a specific runbook by selecting that runbook from the Runbooks page in your Automation account, and then selecting the Jobs tile. 此操作将打开“作业”页。 This action presents the Jobs page. 在此页中可以单击作业记录以查看其详细信息和输出。From here, you can click the job record to view its details and output.

自动化帐户作业页

查看作业摘要Viewing the job summary

在上述作业摘要中可以查看为特定 Runbook 创建的所有作业的列表及其最新状态。The job summary described above allows you to look at a list of all the jobs that have been created for a particular runbook and their most recent status. 若要查看某个作业的详细信息和输出,请在列表中单击其名称。To see detailed information and output for a job, click its name in the list. 作业的详细视图包括提供给该作业的 Runbook 参数值。The detailed view of the job includes the values for the runbook parameters that have been provided to that job.

可以使用以下步骤查看 Runbook 的作业。You can use the following steps to view the jobs for a runbook.

  1. 在 Azure 门户中,选择“自动化” ,然后选择自动化帐户的名称。In the Azure portal, select Automation and then select the name of an Automation account.
  2. 在中心内的“过程自动化”下,选择“Runbook”。 From the hub, select Runbooks under Process Automation.
  3. 在“Runbook”页上的列表中选择一个 Runbook。 On the Runbooks page, select a runbook from the list.
  4. 在所选 runbook 的页上,单击“作业”磁贴 。On the page for the selected runbook, click the Jobs tile.
  5. 单击列表中的某个作业即可在 Runbook 作业详细信息页上查看其详细信息和输出。Click one of the jobs in the list and view its details and output on the runbook job details page.

使用 PowerShell 检索作业状态Retrieving job status using PowerShell

可以使用 Get-AzureRmAutomationJob 检索为 Runbook 创建的作业和特定作业的详细信息。You can use the Get-AzureRmAutomationJob to retrieve the jobs created for a runbook and the details of a particular job. 如果在 PowerShell 中使用 Start-AzureRmAutomationRunbook 启动 Runbook,则会返回生成的作业。If you start a runbook with PowerShell using Start-AzureRmAutomationRunbook, then it returns the resulting job. 使用 Get-AzureRmAutomationJobOutput 可以获取作业的输出。Use Get-AzureRmAutomationJobOutput to get a job’s output.

以下示例获取某个示例 Runbook 的最后一个作业,并显示其状态、为 Runbook 参数提供的值以及该作业的输出。The following example gets the last job for a sample runbook and displays its status, the values provided for the runbook parameters, and the job output.

$job = (Get-AzureRmAutomationJob –AutomationAccountName "MyAutomationAccount" `
–RunbookName "Test-Runbook" -ResourceGroupName "ResourceGroup01" | sort LastModifiedDate –desc)[0]
$job.Status
$job.JobParameters
Get-AzureRmAutomationJobOutput -ResourceGroupName "ResourceGroup01" `
–AutomationAccountName "MyAutomationAcct" -Id $job.JobId –Stream Output

以下示例检索特定作业的输出并返回每个记录。The following example retrieves the output for a specific job and returns each record. 如果某个记录存在异常,脚本将会写入该异常而不是值。If there is an exception for one of the records, the script writes the exception instead of the value. 此行为非常有用,因为异常可以提供在输出过程中正常情况下可能无法记录的其他信息。This behavior is useful, as exceptions can provide additional information that might not be logged normally during output.

$output = Get-AzureRmAutomationJobOutput -AutomationAccountName <AutomationAccountName> -Id <jobID> -ResourceGroupName <ResourceGroupName> -Stream "Any"
foreach($item in $output)
{
    $fullRecord = Get-AzureRmAutomationJobOutputRecord -AutomationAccountName <AutomationAccountName> -ResourceGroupName <ResourceGroupName> -JobId <jobID> -Id $item.StreamRecordId
    if ($fullRecord.Type -eq "Error")
    {
        $fullRecord.Value.Exception
    }
    else
    {
    $fullRecord.Value
    }
}

从活动日志中获取详细信息Getting details from the Activity log

可以从自动化帐户的活动日志中检索 Runbook 详细信息,例如启动该 Runbook 的人员或帐户。You can retrieve runbook details, such as the person or account that started the runbook, from the Activity log for the Automation account. 以下 PowerShell 示例提供运行指定 Runbook 的最后一个用户。The following PowerShell example provides the last user to run the specified runbook.

$SubID = "00000000-0000-0000-0000-000000000000"
$AutomationResourceGroupName = "MyResourceGroup"
$AutomationAccountName = "MyAutomationAccount"
$RunbookName = "MyRunbook"
$StartTime = (Get-Date).AddDays(-1)
$JobActivityLogs = Get-AzureRmLog -ResourceGroupName $AutomationResourceGroupName -StartTime $StartTime `
                                | Where-Object {$_.Authorization.Action -eq "Microsoft.Automation/automationAccounts/jobs/write"}

$JobInfo = @{}
foreach ($log in $JobActivityLogs)
{
    # Get job resource
    $JobResource = Get-AzureRmResource -ResourceId $log.ResourceId

    if ($JobInfo[$log.SubmissionTimestamp] -eq $null -and $JobResource.Properties.runbook.name -eq $RunbookName)
    {
        # Get runbook
        $Runbook = Get-AzureRmAutomationJob -ResourceGroupName $AutomationResourceGroupName -AutomationAccountName $AutomationAccountName `
                                            -Id $JobResource.Properties.jobId | ? {$_.RunbookName -eq $RunbookName}

        # Add job information to hashtable
        $JobInfo.Add($log.SubmissionTimestamp, @($Runbook.RunbookName,$Log.Caller, $JobResource.Properties.jobId))
    }
}
$JobInfo.GetEnumerator() | sort key -Descending | Select-Object -First 1

在 Runbook 之间共享资源Sharing resources among runbooks

为了在云中的所有 Runbook 之间共享资源,Azure 自动化会暂时卸载或停止已运行三小时以上的所有作业。To share resources among all runbooks in the cloud, Azure Automation temporarily unloads or stops any job that has run for more than three hours. PowerShell RunbookPython Runbook 的作业将会停止且不会重启,作业状态变为“已停止”。 Jobs for PowerShell runbooks and Python runbooks are stopped and not restarted, and the job status becomes Stopped.

对于长时间运行的任务,建议使用混合 Runbook 辅助角色。For long-running tasks, it's recommended to use a Hybrid Runbook Worker. 混合 Runbook 辅助角色不受公平份额限制,并且不会限制 runbook 的执行时间。Hybrid Runbook Workers aren't limited by fair share, and don't have a limitation on how long a runbook can execute. 其他作业限制适用于 Azure 沙盒和混合 Runbook 辅助角色。The other job limits apply to both Azure sandboxes and Hybrid Runbook Workers. 虽然混合 Runbook 辅助角色不受 3 小时公平份额限制的约束,但你应该开发在辅助角色上运行的 Runbook,以便在出现意外的本地基础结构问题时支持重启。While Hybrid Runbook Workers aren't limited by the 3-hour fair share limit, you should develop runbooks to run on the workers that support restarts from unexpected local infrastructure issues.

另一种做法是使用子 Runbook 来优化某个 Runbook。Another option is to optimize a runbook by using child runbooks. 例如,你的 Runbook 可能会循环访问多个资源上的同一个函数,例如针对多个数据库执行某个数据库操作。For example, your runbook might loop through the same function on several resources, such as a database operation on several databases. 可将此函数移到某个子 Runbook,并让 Runbook 使用 Start-AzAutomationRunbook 调用此函数。You can move this function to a child runbook and have your runbook call it using Start-AzAutomationRunbook. 子 Runbook 在单独的进程中并行执行。Child runbooks execute in parallel in separate processes.

使用子 Runbook 可以减少完成父 Runbook 所需的总时间。Using child runbooks decreases the total amount of time for the parent runbook to complete. 如果 Runbook 仍然包含完成子级后要执行的操作,该 Runbook 可以使用 Get-AzRmAutomationJob cmdlet 来检查子 Runbook 的作业状态。Your runbook can use the Get-AzRmAutomationJob cmdlet to check the job status for a child runbook if it still has operations to perform after the child completes.

后续步骤Next steps