Azure Webhook获取虚拟机状态

时间:2018-11-09 07:15:54

标签: azure automation virtual-machine azure-runbook

我正在尝试做一个返回计算机状态的Runbook / Webhook。我最后注意到的是

Get-AzureRmVM

仅返回2个资源组。哪里

Get-AzureRmResource

返回更多,但不是全部返回! 我对我的资源组名称有把握,但是仍然说找不到资源组“ groupName”。当我尝试使用特定名称运行

 Get-AzureRmVM -ResourceGroupName groupName

虽然我的其他启动和停止运行手册都可以正常工作,但是我很困惑,我看不到两组之间的区别。

PS:我正在使用Azure Run As Connection

param
(
    [Parameter (Mandatory = $false)]
    [object] $WebhookData
)
if ($WebhookData) {

    $vms = (ConvertFrom-Json -InputObject $WebhookData.RequestBody)

    Write-Output "Authenticating to Azure with service principal and certificate"
    $ConnectionAssetName = "AzureRunAsConnection"
    Write-Output "Get connection asset: $ConnectionAssetName" 

    $Conn = Get-AutomationConnection -Name $ConnectionAssetName
            if ($Conn -eq $null)
            {
                throw "Could not retrieve connection asset: $ConnectionAssetName. Check that this asset exists in the Automation account."
            }
            Write-Output "Authenticating to Azure with service principal." 
            Add-AzureRmAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint | Write-Output

        # Start each virtual machine
        foreach ($vm in $vms)
        {
            $vmName = $vm.Name
            Write-Output "Checking $vmName"

            $vmstatus = Get-AzureRmVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroup -Status# | Select-Object -ExpandProperty StatusesText | ConvertFrom-Json

            #select code index and convert to $vmpowerstate
            $vmPowerState = $vmstatus#[1].Code
            #Write-Output "Resource Group: $vmResourceGroupName", ("VM Name: " + $VM.Name), "Status: $VMStatusDetail" `n
            Write-Output ("VM Name: " + $vmName), "Status: $vmPowerState" `n
        }
}
else {
    write-Error "This is webhook only."
}

1 个答案:

答案 0 :(得分:0)

因为您的资源组位于不同的订阅中。

如@ et3rnal所述,

  

我有2个订阅,并且Get-AzureRmVM仅返回2个虚拟机,因为其余的都是经典的。我在这个运行手册中创建的自动化帐户是另一个帐户,我可以在概述中看到它吗?与其他订阅中用于启动/停止机器的机器相同!

更新

如果要获取虚拟机的PowerState,可以尝试以下命令,在您的情况下,只需将其放入循环中即可,$PowerState是PowerState。

$status = Get-AzureRmVM -Name <VM Name> -ResourceGroupName <Resource Group Name> -Status
$PowerState = ($status.Statuses | Where-Object {$_.Code -like "PowerState/*"}).DisplayStatus

enter image description here

Update2

1。对于经典VM,我们需要使用azure ASM powershell module命令,您可以尝试Get-AzureVM,也许在该链接中的Example 3: Display a table of virtual machine statuses会有所帮助。

2。另一种选择是将经典VM(ASM)迁移到ARM,然后使用ARM命令Get-AzureRmVM

参考文献:

相关问题