教程:创建 PowerShell RunbookTutorial: Create a PowerShell runbook

本教程介绍了如何在 Azure 自动化中创建 PowerShell RunbookThis tutorial walks you through the creation of a PowerShell runbook in Azure Automation. 基于 Windows PowerShell 的 PowerShell Runbook。PowerShell runbooks are based on Windows PowerShell. 可以在 Azure 门户中使用文本编辑器直接编辑 Runbook 的代码。You can directly edit the code of the runbook using the text editor in the Azure portal.

  • 创建简单的 PowerShell RunbookCreate a simple PowerShell runbook
  • 测试并发布 RunbookTest and publish the runbook
  • 运行 Runbook 作业并跟踪其状态Run and track the status of the runbook job
  • 更新 Runbook 以使用 Runbook 参数启动 Azure 虚拟机Update the runbook to start an Azure virtual machine with runbook parameters

先决条件Prerequisites

要完成本教程,需要以下各项:To complete this tutorial, you need the following:

  • Azure 订阅。Azure subscription. 如果还没有 Azure 订阅,可注册一个试用版订阅If you don't have one yet, you can sign up for a Trial Subscription.
  • 自动化帐户 ,用来保存 Runbook 以及向 Azure 资源进行身份验证。Automation account to hold the runbook and authenticate to Azure resources. 此帐户必须有权启动和停止虚拟机。This account must have permission to start and stop the virtual machine.
  • Azure 虚拟机。An Azure virtual machine. 由于需要停止并启动此虚拟机,因此它不应当是生产 VM。Since you stop and start this machine, it shouldn't be a production VM.
  • 如果需要,请导入 Azure 模块更新模块,具体取决于所用的 cmdlet。If necessary, import Azure modules or update modules based on the cmdlets that you use.

与 PowerShell 工作流 Runbook 的差异Differences from PowerShell Workflow runbooks

PowerShell Runbook 与 PowerShell 工作流 Runbook 具有相同的生命周期、功能和管理方式。PowerShell runbooks have the same lifecycle, capabilities, and management as PowerShell Workflow runbooks. 但是,它们也存在一些差异和限制。However, there are some differences and limitations.

特征Characteristic PowerShell RunbookPowerShell Runbooks PowerShell 工作流 RunbookPowerShell Workflow Runbooks
SpeedSpeed 不使用编译步骤,因此运行速度较快。Run fast as they don't use a compilation step. 运行速度更慢。Run more slowly.
检查点Checkpoints 不支持检查点。Don't support checkpoints. PowerShell Runbook 只能从头开始恢复操作。A PowerShell runbook can only resume operation from the beginning. 使用检查点,使工作簿可以从任意位置恢复操作。Use checkpoints, which allow a workbook to resume operation from any point.
命令执行Command Execution 仅支持串行执行。Support serial execution only. 支持串行和并行执行。Support both serial and parallel execution.
RunspaceRunspace 单个运行空间运行脚本中的所有内容。A single runspace runs everything in a script. 一个单独的运行空间可用于活动、命令或脚本块。A separate runspace can be used for an activity, a command, or a script block.

除这些差异外,PowerShell Runbook 还与 PowerShell 工作流 Runbook 存在一些语法差异In addition to these differences, PowerShell runbooks have some syntactic differences from PowerShell Workflow runbooks.

步骤 1 - 创建 RunbookStep 1 - Create runbook

首先创建一个将输出文本 Hello World 的简单 Runbook。Start by creating a simple runbook that outputs the text Hello World.

  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。Create a new runbook by selecting Create a runbook.

  4. 将该 Runbook 命名为 MyFirstRunbook-PowerShellGive the runbook the name MyFirstRunbook-PowerShell.

  5. 在本例中,我们将创建一个 PowerShell RunbookIn this case, you're going to create a PowerShell runbook. 对于“Runbook 类型”,请选择“PowerShell”。Select PowerShell for Runbook type.

  6. 单击“创建”以创建 Runbook 并打开文本编辑器 。Click Create to create the runbook and open the textual editor.

步骤 2 - 将代码添加到 RunbookStep 2 - Add code to the runbook

可以直接将代码键入 Runbook 中,或者通过“库”控件选择 cmdlet、Runbook 和资产,并使用任何相关的参数将它们添加到 Runbook。You can either type code directly into the runbook, or you can select cmdlets, runbooks, and assets from the Library control and have them added to the runbook with any related parameters. 对于本教程,请直接在 Runbook 中键入代码。For this tutorial, you're going to type code directly into the runbook.

  1. Runbook 当前是空的。Your runbook is currently empty. 在脚本正文中键入 Write-Output "Hello World"Type Write-Output "Hello World" in the body of the script.

    Hello World

  2. 通过单击“保存” 保存 Runbook。Save the runbook by clicking Save.

步骤 3 - 测试 Runbook Step 3 - Test the runbook

在发布 Runbook 使其可在生产中使用之前,应对其进行测试,确保其能正常运行。Before you publish the runbook to make it available in production, you should test it to make sure that it works properly. 测试 Runbook 时将运行其“草稿”版本,你可以通过交互方式查看其输出。Testing a runbook runs its Draft version and allows you to view its output interactively.

  1. 单击“测试窗格” 打开测试窗格。Click Test pane to open the Test pane.

  2. 单击“启动”以启动测试 。Click Start to start the test. 这应该是唯一的已启用选项。This should be the only enabled option.

  3. 请注意,此时会创建一个 Runbook 作业并在窗格中显示其状态。Note that a runbook job is created and its status is displayed in the pane.

    作业状态一开始为“排队”,表明作业正在等待云中的 Runbook 辅助角色变为可用状态。The job status starts as Queued, indicating that the job is waiting for a runbook worker in the cloud to become available. 在某个辅助角色认领该作业后,其状态会变为“正在启动”。The status changes to Starting when a worker claims the job. 最后,当 Runbook 开始实际运行时,其状态会变为“正在运行”。Finally, the status becomes Running when the runbook actually starts to run.

  4. Runbook 作业完成后,“测试”窗格会显示其输出。When the runbook job completes, the Test pane displays its output. 在本例中,你会看到 Hello WorldIn this case, you see Hello World.

    测试窗格输出

  5. 关闭测试窗格以返回到画布。Close the Test pane to return to the canvas.

步骤 4 - 发布和启动 RunbookStep 4 - Publish and start the runbook

创建的 Runbook 仍处于“草稿”模式。The runbook that you have created is still in Draft mode. 必须先将它发布,然后才能在生产环境中运行它。It needs to be published before you can run it in production. 当发布 Runbook 时,可以用草稿版本覆盖现有的已发布版本。When you publish a runbook, you overwrite the existing Published version with the Draft version. 在本例中,还没有已发布版本,因为刚刚创建 Runbook。In this case, you don't have a Published version yet because you just created the runbook.

  1. 单击“发布”以发布该 Runbook,并在出现提示时单击“是” 。Click Publish to publish the runbook and then Yes when prompted.

  2. 在“Runbook”页中向左滚动以查看该 Runbook,请注意,“创作状态”值设置为“已发布” 。Scroll left to view the runbook on the Runbooks page, and note that the Authoring Status value is set to Published.

  3. 向右滚动查看“MyFirstRunbook-PowerShell”的页。Scroll back to the right to view the page for MyFirstRunbook-PowerShell.

    顶部的选项现在可用于启动 Runbook、计划将来的启动时间,或创建一个 webhook 以便通过 HTTP 调用来启动 Runbook。The options across the top allow you to start the runbook now, schedule a future start time, or create a webhook so that the runbook can be started through an HTTP call.

  4. 选择“启动”,并在出现提示时选择“是” 启动 runbook。Select Start and then Yes when prompted to start the runbook.

  5. 此时会为已创建的 Runbook 作业打开一个“作业”窗格。A Job pane is opened for the runbook job that has been created. 可以关闭此窗格,不过,暂时最好是使其保持打开状态,以便可以观察作业的进度。Although you can close this pane, leave it open right now so that you can watch the job's progress. 作业状态显示在“作业摘要”中,其中描述了测试 Runbook 时会出现的可能状态。The job status is shown in Job Summary, and possible statuses are as described for testing the runbook.

    作业摘要

  6. Runbook 状态显示为“已完成”后,单击“输出”打开“输出”页,可以看到其中显示了 Hello WorldOnce the runbook status shows Completed, click Output to open the Output page, where you can see Hello World displayed.

    作业输出

  7. 关闭“输出”页。Close the Output page.

  8. 单击“所有日志”打开 Runbook 作业的“流”窗格。Click All Logs to open the Streams pane for the runbook job. 在输出流中应该只会看到 Hello WorldYou should only see Hello World in the output stream.

    请注意,“流”窗格可以显示 Runbook 作业的其他流,例如,详细流和错误流(如果 Runbook 向其写入内容)。Note that the Streams pane can show other streams for a runbook job, such as Verbose and Error streams, if the runbook writes to them.

    所有日志

  9. 关闭“流”窗格和“作业”窗格,返回到“MyFirstRunbook-PowerShell”页。Close the Streams pane and the Job pane to return to the MyFirstRunbook-PowerShell page.

  10. 在“详细信息”下单击“作业”,打开此 Runbook 的“作业”页 。Under Details, click Jobs to open the Jobs page for this runbook. 此页列出你的 Runbook 创建的所有作业。This page lists all the jobs created by your runbook. 由于只将该作业运行了一次,应该只会看到一个列出的作业。You should only see one job listed, since you have only run the job once.

作业列表

  1. 单击作业名称,以打开你在启动 Runbook 时查看过的同一“作业”窗格。Click the job name to open the same Job pane that you viewed when you started the runbook. 使用此窗格可查看为 Runbook 创建的任何作业的详细信息。Use this pane to view the details of any job created for the runbook.

步骤 5 - 添加身份验证来管理 Azure 资源Step 5 - Add authentication to manage Azure resources

已经测试并发布 Runbook,但到目前为止它不执行任何有用的操作。You've tested and published your runbook, but so far it doesn't do anything useful. 需要让其管理 Azure 资源。You want to have it manage Azure resources. 为此,Runbook 必须能够使用在创建自动化帐户时自动创建的运行方式帐户进行身份验证。To do this, the runbook must be able to authenticate using the Run As account that was automatically created when you created your Automation account.

如以下示例中所示,运行方式帐户连接是使用 Connect-AzAccount cmdlet 建立的。As shown in the example below, the Run As connection is made with the Connect-AzAccount cmdlet. 如果跨多个订阅管理资源,需要结合 AzContext 参数使用 Get-AzContextIf you are managing resources across multiple subscriptions, you need to use the AzContext parameter with Get-AzContext.

备注

对于 PowerShell Runbook,Add-AzAccountAdd-AzureRMAccountConnect-AzAccount 的别名。For PowerShell runbooks, Add-AzAccount and Add-AzureRMAccount are aliases for Connect-AzAccount. 可以使用这些 cmdlet,也可以在自动化帐户中将模块更新为最新版本。You can use these cmdlets or you can update your modules in your Automation account to the latest versions. 即使刚刚创建了一个新的自动化帐户,也可能需要更新你的模块。You might need to update your modules even if you have just created a new Automation account.

# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process

$connection = Get-AutomationConnection -Name AzureRunAsConnection

# Wrap authentication in retry logic for transient network failures
$logonAttempt = 0
while(!($connectionResult) -and ($logonAttempt -le 10))
{
    $LogonAttempt++
    # Logging in to Azure...
    $connectionResult = Connect-AzAccount `
                            -ServicePrincipal `
                            -Tenant $connection.TenantID `
                            -ApplicationId $connection.ApplicationID `
                            -CertificateThumbprint $connection.CertificateThumbprint `
                -Environment AzureChinaCloud

    Start-Sleep -Seconds 30
}

$AzureContext = Get-AzSubscription -SubscriptionId $connection.SubscriptionID

Get-AzVM -ResourceGroupName myResourceGroup -AzContext $AzureContext
  1. 通过单击 MyFirstRunbook-PowerShell 页上的“编辑”打开文本编辑器。Open the textual editor by clicking Edit on the MyFirstRunbook-PowerShell page.

  2. 不再需要 Write-Output 行。You don't need the Write-Output line any longer. 请直接删除它。Just go ahead and delete it.

  3. 键入或者复制并粘贴以下代码,该代码使用自动化运行方式帐户来处理身份验证。Type or copy and paste the following code, which handles the authentication with your Automation Run As account.

    # Ensures you do not inherit an AzContext in your runbook
    Disable-AzContextAutosave -Scope Process
    
    $connection = Get-AutomationConnection -Name AzureRunAsConnection
    
    while(!($connectionResult) -and ($logonAttempt -le 10))
    {
        $LogonAttempt++
        # Logging in to Azure...
        $connectionResult = Connect-AzAccount `
                                -ServicePrincipal `
                                -Tenant $connection.TenantID `
                                -ApplicationId $connection.ApplicationID `
                                -CertificateThumbprint $connection.CertificateThumbprint `
                    -Environment AzureChinaCloud
    
        Start-Sleep -Seconds 30
    }
    
  4. 单击“测试”窗格,以便测试 Runbook。Click Test pane so that you can test the runbook.

  5. 单击“启动”以启动测试 。Click Start to start the test. 完成后,你应该会看到类似以下内容的输出,它显示了帐户的基本信息。Once it completes, you should see output similar to the following, displaying basic information from your account. 此输出确认运行方式帐户有效。This output confirms that the Run As Account is valid.

    Authenticate

步骤 6 – 添加用于启动虚拟机的代码Step 6 - Add code to start a virtual machine

现在 Runbook 正在向 Azure 订阅进行身份验证,你可以管理资源。Now that your runbook is authenticating to your Azure subscription, you can manage resources. 让我们添加一项命令,用于启动虚拟机。Let's add a command to start a virtual machine. 可以在 Azure 订阅中选取任何虚拟机,但暂时只需在 Runbook 中对该名称进行硬编码。You can pick any virtual machine in your Azure subscription, and just hard-code that name in the runbook for now.

  1. 在 Runbook 脚本中,添加 Start-AzVM cmdlet 来启动虚拟机。To your runbook script, add the Start-AzVM cmdlet to start the virtual machine. 如下所示,该 cmdlet 启动名为 VMName 的虚拟机以及名为 ResourceGroupName 的资源组。As shown below, the cmdlet starts a virtual machine with the name VMName and with a resource group named ResourceGroupName.

    # Ensures you do not inherit an AzContext in your runbook
    Disable-AzContextAutosave -Scope Process
    
    $connection = Get-AutomationConnection -Name AzureRunAsConnection
    while(!($connectionResult) -and ($logonAttempt -le 10))
    {
        $LogonAttempt++
        # Logging in to Azure...
        $connectionResult = Connect-AzAccount `
                                -ServicePrincipal `
                                -Tenant $connection.TenantID `
                                -ApplicationId $connection.ApplicationID `
                                -CertificateThumbprint $connection.CertificateThumbprint `
                    -Environment AzureChinaCloud
    
        Start-Sleep -Seconds 30
    }
    
    Start-AzVM -Name 'VMName' -ResourceGroupName 'ResourceGroupName'
    
  2. 保存 Runbook,并单击“测试”窗格,以便可以测试 Runbook。Save the runbook and then click Test pane so that you can test it.

  3. 单击“启动”,开始测试。Click Start to begin the test. 完成后,确保虚拟机已启动。Once it completes, make sure that the virtual machine has started.

步骤 7 - 添加输入参数Step 7 - Add an input parameter

Runbook 当前会启动已在 Runbook 中硬编码的虚拟机。Your runbook currently starts the virtual machine that you hard-coded in the runbook. 如果在启动 Runbook 时指定虚拟机,该 Runbook 会更有用。The runbook is more useful if you specify the virtual machine when the runbook is started. 让我们向 Runbook 中添加输入参数,以提供该功能。Let's add input parameters to the runbook to provide that functionality.

  1. 在文本编辑器中修改 Start-AzVM cmdlet,以便对参数 VMNameResourceGroupName 使用变量。In the textual editor, modify the Start-AzVM cmdlet to use variables for the parameters VMName and ResourceGroupName.

    Param(
     [string]$VMName,
     [string]$ResourceGroupName
    )
    # Ensures you do not inherit an AzContext in your runbook
    Disable-AzContextAutosave -Scope Process
    
    $connection = Get-AutomationConnection -Name AzureRunAsConnection
    while(!($connectionResult) -and ($logonAttempt -le 10))
    {
        $LogonAttempt++
        # Logging in to Azure...
        $connectionResult = Connect-AzAccount `
                                -ServicePrincipal `
                                -Tenant $connection.TenantID `
                                -ApplicationId $connection.ApplicationID `
                                -CertificateThumbprint $connection.CertificateThumbprint `
                    -Environment AzureChinaCloud
    
        Start-Sleep -Seconds 30
    }
    
    Start-AzVM -Name $VMName -ResourceGroupName $ResourceGroupName
    
  2. 保存 Runbook 并打开“测试”窗格。Save the runbook and open the Test pane. 现在可以为在测试中使用的两个输入变量提供值。You can now provide values for the two input variables that you use in the test.

  3. 关闭“测试”窗格。Close the Test pane.

  4. 单击“发布”以发布 Runbook 的新版本 。Click Publish to publish the new version of the runbook.

  5. 停止前面启动的虚拟机。Stop the virtual machine that you started previously.

  6. 单击“启动”以启动 Runbook ResourceGroupNameClick Start to start the runbook.

  7. 键入要启动的虚拟机的“VMNAME”和“RESOURCEGROUPNAME”值,然后单击“确定”。Type in the values for VMNAME and RESOURCEGROUPNAME for the virtual machine that you're going to start, and then click OK.

    传递参数

  8. Runbook 完成后,确保虚拟机已启动。When the runbook completes, ensure that the virtual machine has been started.

后续步骤Next steps