Search code examples
azureazure-powershellazure-runbook

Powershell Script continues to ask me to use Select-AzureSubscription although I have called it


I have an Azure runbook where I am trying to deallocate VMs. When I run the runbook I get the error

Stop-AzureVM : No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to 
set the default subscription.

I have used the below in my script.

Add-AzureRmAccount
Select-AzureRMSubscription

After calling the select, it prints out

PSComputerName        : localhost
PSSourceJobInstanceId : 
Account               : 
Environment           : 
Subscription          : 
Tenant                :

with the correct subscrption and tenant information so it seems the select is working correctly, but for some reason I still cannot use the Stop-AzureVM cmdlet.

Any ideas?


Solution

  • The command Stop-AzureVM is Azure Service Management PowerShell command. It just can be used to stop Azure classic VM. But the command Add-AzureRmAccount is Azure Resource Management PowerShell command. After running the command, we just can manage Azure Resource Management resources. For more details, please refer to here and here.

    So with Azure ARM VM, please use the command Stop-AzureRmVM to stop it. Meanwhile, regarding how to stop Azure classic VM, please refer to the following steps

    1. Create Azure Classic Run As Account

    2. Script

    $ConnectionAssetName = "AzureClassicRunAsConnection"
    # Get the connection
    $Conn = Get-AutomationConnection -Name $ConnectionAssetName
    
    # Authenticate to Azure with certificate
    $CertificateAssetName = $Conn.CertificateAssetName
    $AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
    Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert 
    Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
    
    #stop VM
    Stop-AzureVM -ServiceName "ContosoService01" -Name "MyVM" -Force
    

    Besides, regarding how to check if the VM is classic, please refer to the blog