Powershell 脚本继续要求我使用 Select-AzureSubscription,尽管我已经调用了它

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

我有一本 Azure 运行手册,我在其中尝试解除分配 VM。当我 运行 运行 这本书时,我得到了错误

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

我在脚本中使用了以下内容。

Add-AzureRmAccount
Select-AzureRMSubscription

调用select后,打印出

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

使用正确的订阅和租户信息,因此 select 似乎工作正常,但出于某种原因我仍然无法使用 Stop-AzureVM cmdlet。

有什么想法吗?

尝试运行以下:

Get-Module AzureRm.Profile -ListAvailable

当模块有多个实例时,可能会出现此问题。如果有多个实例,请删除旧模块并保留新模块。

删除旧模块:Uninstall-Module -Name AzureRm.Profile -RequiredVersion 4.6.0#(olderversion if you have any)

命令Stop-AzureVM是Azure服务管理PowerShell命令。它仅可用于停止 Azure 经典 VM。但是命令 Add-AzureRmAccount 是 Azure 资源管理 PowerShell 命令。 运行命令后,我们就可以管理Azure资源管理资源了。详情请参考here and here.

因此对于 Azure ARM VM,请使用命令 Stop-AzureRmVM 停止它。同时,关于如何停止Azure经典VM,请参考以下步骤

  1. 创建Azure Classic Run As Account

  2. 脚本

$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

另外,关于如何查看虚拟机是否经典,请参考blog