我的第一个 PowerShell RunbookMy first PowerShell runbook

本教程指导你在 Azure 自动化中创建 PowerShell RunbookThis tutorial walks you through the creation of a PowerShell runbook in Azure Automation. 从一个简单的 Runbook 开始,将测试和发布该 Runbook,同时了解如何跟踪 Runbook 作业的状态。You start with a simple runbook that you test and publish while you learn how to track the status of the runbook job. 然后,通过修改 Runbook 来实际管理 Azure 资源,这种情况下会启动 Azure 虚拟机。Then you modify the runbook to actually manage Azure resources, in this case starting an Azure virtual machine. 最后,通过添加 Runbook 参数使此 Runbook 更稳健。Lastly, you make the runbook more robust by adding runbook parameters.


若要完成本教程,需要满足以下先决条件:To complete this tutorial, you need the following prerequisites:

  • Azure 订阅。Azure subscription. 如果没有订阅,可注册试用版If you don't have one yet, you can sign up for a Trial.
  • 自动化帐户 ,用来保存 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。You stop and start this machine so it shouldn't be a production VM.

创建新的 RunbookCreate new runbook

首先创建一个输出文本 Hello World 的简单 Runbook 。You 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 的列表。 Click Runbooks under Process Automation to open the list of runbooks.
  3. 通过单击“+ 添加 Runbook”按钮,并单击“创建新 Runbook”,创建一个新 Runbook 。Create a new runbook by clicking the + Add a runbook button and then Create a new runbook.
  4. 将该 Runbook 命名为 MyFirstRunbook-PowerShellGive the runbook the name MyFirstRunbook-PowerShell.
  5. 在本例中,将要创建一个 PowerShell Runbook,因此请选择“Powershell”作为“Runbook 类型” 。In this case, you're going to create a PowerShell runbook so select Powershell for Runbook type.
  6. 单击“创建”以创建 Runbook 并打开文本编辑器 。Click Create to create the runbook and open the textual editor.

将代码添加到 RunbookAdd 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 walkthrough, you type directly in the runbook.

  1. Runbook 当前为空,请在脚本正文中键入 Write-Output "Hello World"Your runbook is currently empty, type Write-Output "Hello World." in the body of the script.

    Hello World

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

测试 runbook Test the runbook

在发布 Runbook 使其可在生产中使用之前,需对其进行测试以确保其能正常工作。Before you publish the runbook to make it available in production, you want to test it to make sure that it works properly. 测试 Runbook 时,可以运行其“草稿”版本并以交互方式查看其输出 。When you test a runbook, you run its Draft version and 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 作业并显示其状态。A runbook job is created and its status displayed.

    作业状态一开始为“排队”,表示正在等待云中的 runbook 辅助角色变为可用状态 。The job status starts as Queued indicating that it's waiting for a runbook worker in the cloud to come available. 在某个辅助角色认领此作业后,作业状态将变为“正在启动”,然后当 Runbook 实际开始运行时,此状态将变为“正在运行” 。It moves to Starting when a worker claims the job, and then Running when the runbook actually starts running.

  4. Runbook 作业完成后,会显示其输出。When the runbook job completes, its output is displayed. 在此示例中,应会显示 Hello World 。In your case, you should see Hello World.


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

发布和启动 RunbookPublish and start the runbook

创建的 Runbook 仍处于“草稿”模式。The runbook that you created is still in Draft mode. 必须先将其发布,然后才能在生产环境中运行。It must 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 your 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,它会显示“已发布”的“创作状态” 。If you scroll left to view the runbook in the Runbooks pane now, it shows an Authoring Status of Published.

  3. 向右滚动查看 MyFirstRunbook-PowerShell的窗格。Scroll back to the right to view the pane for MyFirstRunbook-PowerShell.
    顶部的选项允许我们启动 Runbook、查看 Runbook、计划其在将来的某个时刻启动,或创建 webhook 以使其可以通过 HTTP 调用启动。The options across the top allow us to start the runbook, view the runbook, schedule it to start at some time in the future, or create a webhook so it can be started through an HTTP call.

  4. 由于要启动 Runbook,因此请单击“启动”,并在“启动 Runbook”页打开时单击“确定” 。You want to start the runbook, so click Start and then click Ok when the Start Runbook page opens.

  5. 此时会为你创建的 Runbook 作业打开作业页。A job page is opened for the runbook job that you created. 可以关闭此窗格,但在此示例中,将它保持打开状态,以便查看该作业的进度。You can close this pane, but in this case you leave it open so you can watch the job's progress.

  6. 作业状态显示在“作业摘要”中并且与测试该 Runbook 时看到的状态相匹配 。The job status is shown in Job Summary and matches the statuses that you saw when you tested the runbook.


  7. 此 Runbook 状态显示“已完成”后,立即在“概述”下单击“输出” 。Once the runbook status shows Completed, under Overview click Output. “输出”窗格打开后,可以看到 Hello World 。The Output pane is opened, and you can see your Hello World.


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

  9. 单击“所有日志”打开 Runbook 作业的“流”窗格 。Click All Logs to open the Streams pane for the runbook job. 应该只会在输出流中看到“Hello World”,但此输出也可以显示 runbook 作业的其他流,例如,“详细”和“错误”(如果 runbook 向其写入) 。You should only see Hello World in the output stream, but this output can show other streams for a runbook job such as Verbose and Error if the runbook writes to them.


  10. 关闭“流”页和“作业”页以返回到 MyFirstRunbook-PowerShell 页。Close the Streams page and the Job page to return to the MyFirstRunbook-PowerShell page.

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


  1. 可以单击此作业,打开在启动 Runbook 时查看过的“作业”窗格。You can click this job to open the same Job pane that you viewed when you started the runbook. 这样便可以回溯并查看为特定 runbook 创建的任何作业的详细信息。This action allows you to go back in time and view the details of any job that was created for a particular runbook.

添加身份验证来管理 Azure 资源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. 除非使用在创建自动化帐户时自动创建的运行方式连接对其进行身份验证,否则无法执行此操作。It is not able to do that though unless You have it authenticate using a Run As connection that is automatically created when you create your automation account. 通过 Connect-azurermaccount cmdlet 使用运行方式连接 。You use the Run As connection with the Connect-AzureRmAccount cmdlet. 如果要跨多个订阅管理资源,需要使用 -AzureRmContext 参数以及 Get-AzureRmContextIf you are managing resources across multiple subscriptions, you need to use the -AzureRmContext parameter along with Get-AzureRmContext.

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

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

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

Get-AzureRmVM -ResourceGroupName myResourceGroup -AzureRmContext $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 anymore, so go ahead and delete it.

  3. 键入(或者复制并粘贴)以下代码,对自动化运行方式帐户的身份验证进行处理:Type or copy and paste the following code that handles the authentication with your Automation Run As account:

    # Ensures you do not inherit an AzureRMContext in your runbook
    Disable-AzureRmContextAutosave -Scope Process
    $connection = Get-AutomationConnection -Name AzureRunAsConnection
    Connect-AzureRmAccount -ServicePrincipal -Tenant $connection.TenantID `
    -ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint -EnvironmentName "AzureChinaCloud"


    Add-AzureRmAccountLogin-AzureRmAccount 现在是 Connect-AzureRMAccount 的别名。Add-AzureRmAccount and Login-AzureRmAccount are now aliases for Connect-AzureRMAccount. 如果 Connect-AzureRMAccount cmdlet 不存在,则可以使用 Add-AzureRmAccountLogin-AzureRmAccount,也可以将自动化帐户中的模块更新为最新版本。If the Connect-AzureRMAccount cmdlet does not exist, you can use Add-AzureRmAccount or Login-AzureRmAccount, or you can update your modules in your Automation Account to the latest versions.

  4. 单击“测试” 窗格,以便测试 Runbook。Click Test pane so that you can test the runbook.

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


添加代码以启动虚拟机Add code to start a virtual machine

现在 Runbook 正在向 Azure 订阅进行身份验证,你可以管理资源。Now that your runbook is authenticating to your Azure subscription, you can manage resources. 将添加一个命令,用于启动虚拟机。You add a command to start a virtual machine. 可以在 Azure 订阅中选取任何虚拟机。而现在,需将该名称硬编码到 Runbook。You can pick any virtual machine in your Azure subscription, and for now you hardcode that name in the runbook.

  1. 在 Connect-AzureRmAccount 后面键入 Start-AzureRmVM -Name 'VMName' -ResourceGroupName 'NameofResourceGroup'(提供要启动的虚拟机的名称和资源组名称) 。After Connect-AzureRmAccount, type Start-AzureRmVM -Name 'VMName' -ResourceGroupName 'NameofResourceGroup' providing the name and Resource Group name of the virtual machine to start.

    # Ensures you do not inherit an AzureRMContext in your runbook
    Disable-AzureRmContextAutosave -Scope Process
    $connection = Get-AutomationConnection -Name AzureRunAsConnection
    Connect-AzureRmAccount -ServicePrincipal -Tenant $connection.TenantID `
    -ApplicationID $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint -EnvironmentName "AzureChinaCloud"
    Start-AzureRmVM -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 start the test. 一旦测试完成后,检查已启动的虚拟机。Once it completes, check that the virtual machine was started.

添加输入参数Add an input parameter

Runbook 当前会启动你在 Runbook 中硬编码的虚拟机,但如果在启动 Runbook 时指定虚拟机,它会更有用。Your runbook currently starts the virtual machine that you hardcoded in the runbook, but it would be more useful if you specify the virtual machine when the runbook is started. 现在将输入参数添加到 Runbook,以提供该功能。You add input parameters to the runbook to provide that functionality.

  1. VMNameResourceGroupName 的参数添加到 Runbook,并将这些变量与 Start-AzureRmVM cmdlet 配合使用,如以下示例所示。Add parameters for VMName and ResourceGroupName to the runbook and use these variables with the Start-AzureRmVM cmdlet as in the following example.

    # Ensures you do not inherit an AzureRMContext in your runbook
    Disable-AzureRmContextAutosave -Scope Process
    $connection = Get-AutomationConnection -Name AzureRunAsConnection
    Connect-AzureRmAccount -ServicePrincipal -Tenant $connection.TenantID `
    -ApplicationID $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint -EnvironmentName "AzureChinaCloud"
    Start-AzureRmVM -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 are used 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 in the previous step.

  6. 单击“确定” 启动 Runbook。Click OK to start the runbook. 键入要启动的虚拟机的 VMNameResourceGroupNameType in the VMName and ResourceGroupName for the virtual machine that you're going to start.

    传递参数Pass Parameter

  7. 一旦 Runbook 完成后,检查已启动的虚拟机。When the runbook completes, check that the virtual machine was started.

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

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

  1. PowerShell Runbook 比 PowerShell 工作流 Runbook 的运行速度更快,因为没有编译步骤。PowerShell runbooks run fast compared to PowerShell Workflow runbooks as they don’t have compilation step.
  2. PowerShell 工作流 runbook 支持检查点。使用检查点,PowerShell 工作流 runbook 可以从 runbook 中的任意点恢复。PowerShell Workflow runbooks support checkpoints, using checkpoints, PowerShell Workflow runbooks can resume from any point in the runbook. PowerShell runbook 仅可从开始处恢复。PowerShell runbooks can only resume from the beginning.
  3. PowerShell 工作流 runbook 支持并行和串行执行。PowerShell Workflow runbooks support parallel and serial execution. PowerShell runbook 仅可按顺序执行命令。PowerShell runbooks can only execute commands serially.
  4. 在 PowerShell 工作流 runbook 中,活动、命令或脚本块可以有自己的运行空间。In a PowerShell Workflow runbook, an activity, a command, or a script block can have its own runspace. 在 PowerShell runbook 中,脚本内的所有内容都在单个运行空间中运行。In a PowerShell runbook, everything in a script runs in a single runspace. 本机 PowerShell Runbook 和 PowerShell 工作流 Runbook 之间还存在一些 语法差异There are also some syntactic differences between a native PowerShell runbook and a PowerShell Workflow runbook.

后续步骤Next steps