如何使用 powershell 重启容器实例

How to restart a container instance using powershell

我正在尝试使用 PowerShell 设置自动化作业以重新启动容器实例。但似乎没有内置的 PowerShell module/cmdlet 来帮助

我可以使用 azure CLI 重启容器实例 (https://docs.microsoft.com/en-us/cli/azure/container?view=azure-cli-latest#az-container-restart)

az container restart --name <name> --resource-group <group>

有没有办法使用 Powershell 做同样的事情。

提前致谢

Azure PowerShell 不提供直接重启容器实例的命令,但我们可以使用 powershell 调用 Azure 管理 API 来重启容器实例作为解决方法。

  1. 在 Azure AD 中注册一个应用程序,为其创建一个客户端密码,记下它的值和应用程序 ID(您可以在概述中找到它):

  1. 为其分配贡献者角色,以便它有权管理您的 Azure 资源:

3.Try 下面的 powershell 脚本重启你的容器实例:

$appid = "<application ID we resistered>"
$appSecret= "<application client secret we created>"
$tenant = "<your tenant ID/NAME>"

$resourceGroup = "<resource group>"
$containerInstanceName = "<containerInstances name>"
$subscrptionId = "<subscription ID>"

$body=@{
    "grant_type"="client_credentials";
    "resource"="https://management.azure.com/";
    "client_id"=$appid;
    "client_secret"=$appSecret
}
 
$result=Invoke-RestMethod -Uri "https://login.windows.net/$tenant/oauth2/token" -Method POST -Body $body 
$accessToken = $result.access_token

Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/$subscrptionId/resourceGroups/$resourceGroup/providers/Microsoft.ContainerInstance/containerGroups/$containerInstanceName/restart?api-version=2018-10-01" -Method POST -Headers @{"Authorization"="Bearer $accessToken"} 

结果: