使用 PowerShell cmdlet 管理 Batch 资源Manage Batch resources with PowerShell cmdlets

通过 Azure Batch PowerShell cmdlet,可以执行许多通过 Batch API、Azure 门户和 Azure 命令行界面 (CLI) 执行的任务并为它们编写脚本。With the Azure Batch PowerShell cmdlets, you can perform and script many of the tasks you carry out with the Batch APIs, the Azure portal, and the Azure Command-Line Interface (CLI). 本文将简要介绍可用于管理 Batch 帐户和处理 Batch 资源(例如池、作业和任务)的 cmdlet。This is a quick introduction to the cmdlets you can use to manage your Batch accounts and work with your Batch resources such as pools, jobs, and tasks.

如需 Batch cmdlet 的完整列表和详细的 cmdlet 语法,请参阅 Azure Batch cmdlet 参考For a complete list of Batch cmdlets and detailed cmdlet syntax, see the Azure Batch cmdlet reference.

本文基于 Az Batch 模块 1.0.0 中的 cmdlet。This article is based on cmdlets in Az Batch module 1.0.0. 建议经常更新 Azure PowerShell 模块以利用服务更新和增强功能。We recommend that you update your Azure PowerShell modules frequently to take advantage of service updates and enhancements.

先决条件Prerequisites

  • 下载并配置 Azure PowerShell 模块Install and configure the Azure PowerShell module. 若要安装特定的 Azure Batch 模块,例如预发行模块,请参阅 PowerShell 库To install a specific Azure Batch module, such as a pre-release module, see the PowerShell Gallery.

  • 运行 Connect-AzAccount cmdlet 连接到订阅(Azure 资源管理器模块中随附了 Azure Batch cmdlet):Run the Connect-AzAccount cmdlet to connect to your subscription (the Azure Batch cmdlets ship in the Azure Resource Manager module):

    Connect-AzAccount -Environment AzureChinaCloud
    
  • 注册到批处理提供程序命名空间Register with the Batch provider namespace. 执行此操作时,只需每个订阅一次You only need to perform this operation once per subscription.

    Register-AzResourceProvider -ProviderNamespace Microsoft.Batch
    

管理批处理帐户和密钥Manage Batch accounts and keys

创建批处理帐户Create a Batch account

New-AzBatchAccount 可在指定的资源组中创建 Batch 帐户。New-AzBatchAccount creates a Batch account in a specified resource group. 如果没有资源组,可以运行 New-AzResourceGroup cmdlet 创建一个资源组。If you don't already have a resource group, create one by running the New-AzResourceGroup cmdlet. Location 参数中指定一个 Azure 区域,例如“中国北部”。Specify one of the Azure regions in the Location parameter, such as "China North". 例如:For example:

New-AzResourceGroup -Name MyBatchResourceGroup -Location "China North"

然后,在该资源组中创建一个 Batch 帐户。Then, create a Batch account in the resource group. 为 <account_name> 中的帐户指定帐户名,并指定资源组的位置和名称。Specify a name for the account in <account_name>, and the location and name of your resource group. 创建 Batch 帐户可能需要一些时间才能完成。Creating the Batch account can take some time to complete. 例如:For example:

New-AzBatchAccount -AccountName <account_name> -Location "China North" -ResourceGroupName <res_group_name>

备注

Batch 帐户名在资源组所在的 Azure 区域中必须唯一,长度为 3 到 24 个字符,并且只能包含小写字母和数字。The Batch account name must be unique to the Azure region for the resource group, contain between 3 and 24 characters, and use lowercase letters and numbers only.

获取帐户访问密钥Get account access keys

Get-AzBatchAccountKeys 显示与 Azure Batch 帐户关联的访问密钥。Get-AzBatchAccountKeys shows the access keys associated with an Azure Batch account. 例如,运行以下命令可获取所创建的帐户的主要密钥和辅助密钥。For example, run the following to get the primary and secondary keys of the account you created.

$Account = Get-AzBatchAccountKeys -AccountName <account_name>

$Account.PrimaryAccountKey

$Account.SecondaryAccountKey

生成新的访问密钥Generate a new access key

New-AzBatchAccountKey 为 Azure Batch 帐户生成新的主要帐户密钥或辅助帐户密钥。New-AzBatchAccountKey generates a new primary or secondary account key for an Azure Batch account. 例如,若要为批处理帐户生成新的主要密钥,请键入:For example, to generate a new primary key for your Batch account, type:

New-AzBatchAccountKey -AccountName <account_name> -KeyType Primary

备注

若要生成新的辅助密钥,请为 KeyType 参数指定“Secondary”。To generate a new secondary key, specify "Secondary" for the KeyType parameter. 必须单独重新生成主要密钥和辅助密钥。You have to regenerate the primary and secondary keys separately.

删除批处理帐户Delete a Batch account

Remove-AzBatchAccount 删除 Batch 帐户。Remove-AzBatchAccount deletes a Batch account. 例如:For example:

Remove-AzBatchAccount -AccountName <account_name>

出现提示时,确认你想要删除该帐户。When prompted, confirm you want to remove the account. 帐户删除可能需要一段时间才能完成。Account removal can take some time to complete.

创建 BatchAccountContext 对象Create a BatchAccountContext object

可以通过共享密钥身份验证或 Azure Active Directory 身份验证进行身份验证,以便管理 Batch 资源。You can authenticate to manage Batch resources using either shared key authentication or Azure Active Directory authentication. 若要使用 Batch PowerShell cmdlet 进行身份验证,需先创建 BatchAccountContext 对象来存储帐户凭据或标识。To authenticate using the Batch PowerShell cmdlets, first create a BatchAccountContext object to store your account credentials or identity. 将 BatchAccountContext 对象传入使用 BatchContext 参数的 cmdlet。You pass the BatchAccountContext object into cmdlets that use the BatchContext parameter.

共享密钥身份验证Shared key authentication

$context = Get-AzBatchAccountKeys -AccountName <account_name>

备注

默认情况下,帐户的主要密钥用于身份验证,但可以通过更改 BatchAccountContext 对象的 KeyInUse 属性,显式选择要使用的密钥:$context.KeyInUse = "Secondary"By default, the account's primary key is used for authentication, but you can explicitly select the key to use by changing your BatchAccountContext object's KeyInUse property: $context.KeyInUse = "Secondary".

Azure Active Directory 身份验证Azure Active Directory authentication

$context = Get-AzBatchAccount -AccountName <account_name>

创建和修改 Batch 资源Create and modify Batch resources

使用 New-AzBatchPoolNew-AzBatchJobNew-AzBatchTask 等 cmdlet 在 Batch 帐户下创建资源。Use cmdlets such as New-AzBatchPool, New-AzBatchJob, and New-AzBatchTask to create resources under a Batch account. 可以使用相应的 Get-Set- cmdlet 来更新现有资源的属性,以及使用 Remove- cmdlet 来删除批处理帐户下的资源。There are corresponding Get- and Set- cmdlets to update the properties of existing resources, and Remove- cmdlets to remove resources under a Batch account.

使用这些 cmdlet 时,除了传递 BatchContext 对象,还需要创建或传递包含详细的资源设置的对象,如以下示例所示。When using many of these cmdlets, in addition to passing a BatchContext object, you need to create or pass objects that contain detailed resource settings, as shown in the following example. 请参阅每个 cmdlet 的详细帮助说明来了解其他示例。See the detailed help for each cmdlet for additional examples.

创建 Batch 池Create a Batch pool

创建或更新 Batch 池时,你需要为计算节点上的操作系统选择云服务配置或虚拟机配置(请参阅节点和池)。When creating or updating a Batch pool, you select either the cloud services configuration or the virtual machine configuration for the operating system on the compute nodes (see Nodes and pools). 如果指定云服务配置,系统会使用一个 Azure 来宾 OS 版本为计算节点创建映像。If you specify the cloud services configuration, your compute nodes are imaged with one of the Azure Guest OS releases. 如果指定虚拟机配置,则可指定一个受支持的 Linux 或 Windows VM 映像(在 Azure 虚拟机市场中列出),或者提供已准备的自定义映像。If you specify the virtual machine configuration, you can either specify one of the supported Linux or Windows VM images listed in the Azure Virtual Machines Marketplace, or provide a custom image that you have prepared.

运行 New-AzBatchPool时,传递 PSCloudServiceConfiguration 或 PSVirtualMachineConfiguration 对象中的操作系统设置。When you run New-AzBatchPool, pass the operating system settings in a PSCloudServiceConfiguration or PSVirtualMachineConfiguration object. 例如,以下代码片段可以在虚拟机配置中创建包含 Standard_A1 大小计算节点的 Batch 池,这些节点包含 Ubuntu Server 18.04-LTS 映像。For example, the following snippet creates a Batch pool with size Standard_A1 compute nodes in the virtual machine configuration, imaged with Ubuntu Server 18.04-LTS. 在这里,VirtualMachineConfiguration 参数指定 $configuration 变量作为 PSVirtualMachineConfiguration 对象。Here, the VirtualMachineConfiguration parameter specifies the $configuration variable as the PSVirtualMachineConfiguration object. BatchContext 参数将先前定义的变量 $context 指定为 BatchAccountContext 对象。The BatchContext parameter specifies a previously defined variable $context as the BatchAccountContext object.

$imageRef = New-Object -TypeName "Microsoft.Azure.Commands.Batch.Models.PSImageReference" -ArgumentList @("UbuntuServer","Canonical","18.04-LTS")

$configuration = New-Object -TypeName "Microsoft.Azure.Commands.Batch.Models.PSVirtualMachineConfiguration" -ArgumentList @($imageRef, "batch.node.ubuntu 18.04")

New-AzBatchPool -Id "mypspool" -VirtualMachineSize "Standard_a1" -VirtualMachineConfiguration $configuration -AutoScaleFormula '$TargetDedicated=4;' -BatchContext $context

通过自动缩放公式计算新池中的目标计算节点数。The target number of compute nodes in the new pool is calculated by an autoscaling formula. 在本示例中,公式为 $TargetDedicated=4,表示池中的计算节点数最多为 4。In this case, the formula is simply $TargetDedicated=4, indicating the number of compute nodes in the pool is 4 at most.

查询池、作业、任务以及其他详细信息Query for pools, jobs, tasks, and other details

使用 Get-AzBatchPoolGet-AzBatchJobGet-AzBatchTask 等 cmdlet 查询在 Batch 帐户下创建的实体。Use cmdlets such as Get-AzBatchPool, Get-AzBatchJob, and Get-AzBatchTask to query for entities created under a Batch account.

查询数据Query for data

例如,使用 Get-AzBatchPools 可查找池。As an example, use Get-AzBatchPools to find your pools. 假设已将 BatchAccountContext 对象存储在 $context中,则默认情况下,此 cmdlet 将查询帐户下的所有池:By default this queries for all pools under your account, assuming you already stored the BatchAccountContext object in $context:

Get-AzBatchPool -BatchContext $context

使用 OData 筛选器Use an OData filter

可以使用 Filter 参数提供 OData 筛选器,以便只查找所需的对象。You can supply an OData filter using the Filter parameter to find only the objects you're interested in. 例如,可以查找 ID 以“myPool”开头的所有池:For example, you can find all pools with IDs starting with "myPool":

$filter = "startswith(id,'myPool')"

Get-AzBatchPool -Filter $filter -BatchContext $context

此方法的灵活性不如在本地管道中使用“Where-Object”。This method is not as flexible as using "Where-Object" in a local pipeline. 但是,该查询将直接发送到批处理服务,因此所有筛选都在服务器端发生,这可以节省 Internet 带宽。However, the query gets sent to the Batch service directly so that all filtering happens on the server side, saving Internet bandwidth.

使用 Id 参数Use the Id parameter

OData 筛选器的替代方法是使用 Id 参数。An alternative to an OData filter is to use the Id parameter. 若要查询 ID 为“myPool”的特定池:To query for a specific pool with id "myPool":

Get-AzBatchPool -Id "myPool" -BatchContext $context

Id 参数仅支持完整 ID 搜索,而不支持通配符或 OData 样式的筛选器。The Id parameter supports only full-ID search; not wildcards or OData-style filters.

使用 MaxCount 参数Use the MaxCount parameter

默认情况下,每个 cmdlet 最多返回 1000 个对象。By default, each cmdlet returns a maximum of 1000 objects. 如果达到此限制,可以优化筛选器以返回更少的对象,或者使用 MaxCount 参数显式设置最大值。If you reach this limit, either refine your filter to bring back fewer objects, or explicitly set a maximum using the MaxCount parameter. 例如:For example:

Get-AzBatchTask -MaxCount 2500 -BatchContext $context

若要去除上限,请 MaxCount 设置为 0 或更小。To remove the upper bound, set MaxCount to 0 or less.

使用 PowerShell 管道Use the PowerShell pipeline

Batch cmdlet 使用 PowerShell 管道在 cmdlet 之间发送数据。Batch cmdlets use the PowerShell pipeline to send data between cmdlets. 这与指定参数的效果相同,但可以更方便地使用多个实体。This has the same effect as specifying a parameter, but makes working with multiple entities easier.

例如,可以查找和显示帐户下的所有任务:For example, find and display all tasks under your account:

Get-AzBatchJob -BatchContext $context | Get-AzBatchTask -BatchContext $context

重新启动(重新引导)池中的每个计算节点:Restart (reboot) every compute node in a pool:

Get-AzBatchComputeNode -PoolId "myPool" -BatchContext $context | Restart-AzBatchComputeNode -BatchContext $context

应用程序包管理Application package management

应用程序包提供将应用程序部署到池中计算节点的简化方式。Application packages provide a simplified way to deploy applications to the compute nodes in your pools. 使用批处理 PowerShell cmdlet,可以上传和管理批处理帐户中的应用程序包,以及将包版本部署到计算节点。With the Batch PowerShell cmdlets, you can upload and manage application packages in your Batch account, and deploy package versions to compute nodes.

创建 应用程序:Create an application:

New-AzBatchApplication -AccountName <account_name> -ResourceGroupName <res_group_name> -ApplicationId "MyBatchApplication"

添加 应用程序包:Add an application package:

New-AzBatchApplicationPackage -AccountName <account_name> -ResourceGroupName <res_group_name> -ApplicationId "MyBatchApplication" -ApplicationVersion "1.0" -Format zip -FilePath package001.zip

设置应用程序的默认版本Set the default version for the application:

Set-AzBatchApplication -AccountName <account_name> -ResourceGroupName <res_group_name> -ApplicationId "MyBatchApplication" -DefaultVersion "1.0"

列出应用程序的包List an application's packages

$application = Get-AzBatchApplication -AccountName <account_name> -ResourceGroupName <res_group_name> -ApplicationId "MyBatchApplication"

$application.ApplicationPackages

删除应用程序包Delete an application package

Remove-AzBatchApplicationPackage -AccountName <account_name> -ResourceGroupName <res_group_name> -ApplicationId "MyBatchApplication" -ApplicationVersion "1.0"

删除应用程序Delete an application

Remove-AzBatchApplication -AccountName <account_name> -ResourceGroupName <res_group_name> -ApplicationId "MyBatchApplication"

备注

在删除某个应用程序之前,必须删除该应用程序的所有应用程序包版本。You must delete all of an application's application package versions before you delete the application. 如果尝试删除当前具有应用程序包的应用程序,会发生“冲突”错误。You will receive a 'Conflict' error if you try to delete an application that currently has application packages.

部署应用程序包Deploy an application package

在创建池时,可以指定一个或多个要部署的应用程序包。You can specify one or more application packages for deployment when you create a pool. 如果创建池时指定包,该包会在节点加入池时部署到每个节点。When you specify a package at pool creation time, it is deployed to each node as the node joins pool. 将节点重新启动或重置映像时,也会部署包。Packages are also deployed when a node is rebooted or reimaged.

创建池时,请指定 -ApplicationPackageReference 选项,以便在池节点加入该池时,将应用程序包部署到这些节点。Specify the -ApplicationPackageReference option when creating a pool to deploy an application package to the pool's nodes as they join the pool. 首先,创建 PSApplicationPackageReference 对象,并使用应用程序 ID 和要部署到池中计算节点的包版本来配置该对象:First, create a PSApplicationPackageReference object, and configure it with the application ID and package version you want to deploy to the pool's compute nodes:

$appPackageReference = New-Object Microsoft.Azure.Commands.Batch.Models.PSApplicationPackageReference

$appPackageReference.ApplicationId = "MyBatchApplication"

$appPackageReference.Version = "1.0"

现在创建配置和池。Now create the configuration and pool. 此示例将 CloudServiceConfiguration 参数与在 $configuration 中初始化的一个 PSCloudServiceConfiguration 类型的对象配合使用,对于“Windows Server 2019”,该参数将 OSFamily 设置为 6,并将 OSVersion 设置为 *This example uses the CloudServiceConfiguration parameter with a PSCloudServiceConfiguration type object initialized in $configuration, which sets the OSFamily to 6 for 'Windows Server 2019' and OSVersion to *. 将包引用对象指定为 ApplicationPackageReferences 选项的参数:Specify the package reference object as the argument to the ApplicationPackageReferences option:

$configuration = New-Object -TypeName "Microsoft.Azure.Commands.Batch.Models.PSCloudServiceConfiguration" -ArgumentList @(6,"*")  # 6 = OSFamily 'Windows Server 2019'
New-AzBatchPool -Id "PoolWithAppPackage" -VirtualMachineSize "Small" -CloudServiceConfiguration $configuration -BatchContext $context -ApplicationPackageReferences $appPackageReference

有关应用程序包的详细信息,可参阅使用 Batch 应用程序包将应用程序部署到计算节点You can find more information on application packages in Deploy applications to compute nodes with Batch application packages.

重要

必须将一个 Azure 存储帐户链接到你的 Batch 帐户才能使用应用程序包。You must link an Azure Storage account to your Batch account to use application packages.

更新池的应用程序包Update a pool's application packages

若要更新分配到现有池的应用程序,请先创建包含所需的属性(应用程序 ID 和包版本)的 PSApplicationPackageReference 对象:To update the applications assigned to an existing pool, first create a PSApplicationPackageReference object with the desired properties (application ID and package version):

$appPackageReference = New-Object Microsoft.Azure.Commands.Batch.Models.PSApplicationPackageReference

$appPackageReference.ApplicationId = "MyBatchApplication"

$appPackageReference.Version = "2.0"

接下来,从批处理中获取池,清除所有现有包,添加新的包引用,并使用新的池设置更新批处理服务:Next, get the pool from Batch, clear out any existing packages, add our new package reference, and update the Batch service with the new pool settings:

$pool = Get-AzBatchPool -BatchContext $context -Id "PoolWithAppPackage"

$pool.ApplicationPackageReferences.Clear()

$pool.ApplicationPackageReferences.Add($appPackageReference)

Set-AzBatchPool -BatchContext $context -Pool $pool

现已更新批处理服务中的池属性。You've now updated the pool's properties in the Batch service. 但是,要将新应用程序包真正部署到池中的计算节点,必须将这些节点重新启动或重置映像。To actually deploy the new application package to compute nodes in the pool, however, you must restart or reimage those nodes. 可以使用以下命令重新启动池中的每个节点:You can restart every node in a pool with this command:

Get-AzBatchComputeNode -PoolId "PoolWithAppPackage" -BatchContext $context | Restart-AzBatchComputeNode -BatchContext $context

提示

可将多个应用程序包部署到池中的计算节点。You can deploy multiple application packages to the compute nodes in a pool. 如果想要添加应用程序包而不是替换当前部署的包,请省略上面的 $pool.ApplicationPackageReferences.Clear() 代码行。If you'd like to add an application package instead of replacing the currently deployed packages, omit the $pool.ApplicationPackageReferences.Clear() line above.

后续步骤Next steps