尽管订阅中有虚拟机,但Get-AzureVM仍返回null

时间:2015-07-22 05:55:54

标签: powershell azure

我正在编写一个脚本,我已从库中下载该脚本以停止在订阅中运行的所有VM。这一直运行到上周,但是当我昨天运行它时,它无法在我的订阅中找到任何虚拟机(虚拟机存在于我的子网中并且正在运行)。脚本如下:

workflow Stop-AllAzureVM
{   
    # Add the credential used to authenticate to Azure. 
    # TODO: Fill in the -Name parameter with the Name of the Automation     PSCredential asset
    # that has access to your Azure subscription.  "myPScredName" is your asset name that reflects an OrgID user
    # like "someuser@somewhere.onmicrosoft.com" that has Co-Admin rights to your subscription.
    $Cred = Get-AutomationPSCredential -Name "myPsCred"

    # Connect to Azure
    Add-AzureAccount -Credential $Cred

    # Select the Azure subscription you want to work against
    # TODO: Fill in the -SubscriptionName parameter with the name of your Azure subscription
    Select-AzureSubscription -SubscriptionName "MySubs"


    # Get all Azure VMs in the subscription that are not stopped and deallocated, and shut them down
    # all at once.
    $VMs = Get-AzureVM | where-object -FilterScript {$_.status -ne 'StoppedDeallocated'}
    if (!$VMs)
    {
        Write-Output "No VM running at the moment"
    }
    else
    {
        Write-Output "VM(s) found running, proceeding for shutdown"
    }
    foreach -parallel ($vm in $VMs)
    {       
        $stopRtn = Stop-AzureVM -Name $VM.Name -ServiceName $VM.ServiceName -force -ea SilentlyContinue
        $count=1
        if(($stopRtn.OperationStatus) -ne 'Succeeded')
        {
            do{
                    Write-Output "Failed to stop $($VM.Name). Retrying in 60 seconds..."
                    sleep 60
                    $stopRtn = Stop-AzureVM -Name $VM.Name -ServiceName $VM.ServiceName -force -ea SilentlyContinue
                    $count++
                }
                while(($stopRtn.OperationStatus) -ne 'Succeeded' -and $count -lt 5)

        }

        if($stopRtn){Write-Output "Stop-AzureVM cmdlet for $($VM.Name) $($stopRtn.OperationStatus) on attempt number $count of 5."}
    }

}

此脚本始终打印"此刻没有VM正在运行"

我在没有任何条件的情况下尝试了Get-AzureVM,但结果是一样的。

我不确定过去几周内是否有任何变化导致了这个问题。

更新-1: 我尝试在脚本中添加以下命令:

$VMs = Get-AzureVM
$subscriptions = Get-AzureSubscription
Write-Output "Found [$($subscriptions.Count)] subscriptions accessible to user"
Write-Output "Found [$($VMs.Count)] VMs in Subscription"

我得到了以下输出:

发现[]用户可以访问的订阅 在Subscription中找到[0] VM 目前没有VM正在运行

所以看起来在我的自动化帐户中发生了一些奇怪的事情,我似乎对它没有任何线索!

1 个答案:

答案 0 :(得分:-1)

对于所有面临此问题的人,不确定这是否是解决此问题的正确方法,但至少作为一种解决方法,我尝试创建一个新的自动化帐户并在其中复制粘贴的相同Runbook,它对我来说工作正常