PowerShell 是管理 Azure 的最好方式之一,經過使用 PowerShell 腳本能夠把不少的工做自動化。好比對於 Azure 上的虛擬機,能夠設置定時關機操做,並在適當的時間把它開機,這樣就能減小虛擬機的運行時間,同時也能爲節能減排作出貢獻。html
PowerShell 的 Azure 模塊中爲咱們提供了不一樣的 API, 早期的 API 叫 ASM(Azure Service Manager)。隨着 Azure 的發展變化,又出現了一套新的 API 叫 ARM(Azure Resource Management)。在這裏,咱們僅介紹如何使用 ARM中 的 API 實現 Azure 上的自動登陸並操做資源。json
使用 PowerShell 自動登陸 Azure 的大致思路是這樣的:首先使用登陸命令在交互式界面下進行登陸操做,而後使用 Save-AzureRmProfile 命令把登陸認證信息保存到本地的文件中。之後在腳本中設置自動登陸時,只需使用這個本地文件就能夠了。session
下面來看看具體的操做過程。加密
在登陸前須要先檢查一下當前的登陸狀態,能夠經過查詢 resource group 來進行間接檢查。spa
執行命令:Get-AzureRmResourceGroup日誌
若是當前沒有登陸,則會查詢失敗並提示咱們須要登陸。code
執行命令:Login-AzureRmAccounthtm
經過彈出的對話框登陸:blog
登陸成功後會顯示帳戶信息:ip
而後再執行一次 Get-AzureRmResourceGroup 命令。
好了,以前的錯誤信息已經沒有了,輸出的結果爲 Resource Group 的列表。
到這裏,就已經登陸成功了。
Save-AzureRmProfile 命令可以把當前 session 的登陸信息保存到文件中,這樣其它的 session 也可使用這個文件進行自動登陸了。
執行命令:Save-AzureRmProfile -Path 「d:\test\myprofile.json」
myprofile.json 是一個普通的文本文件,文件中只有認證信息被加密了,其它的信息都是可讀的。
注意,必定要保護好生成的 myprofile.json 文件,若是泄露出去和別人拿到你的帳戶密碼是同樣的。
經過 Select-AzureRmProfile 命令,能夠從文件中載入用戶的登陸信息而且設置 Azure 的執行上下文。
執行命令:Select-AzureRmProfile –Path 「d:\test\myprofile.json」
其執行結果和運行 Login-AzureRmAccount 命令是同樣的:
如下是重啓 Azure 上的一臺虛機的完整例子:
$profile = "your profile path" $resourceGroupName = "your resource group name" $vmName = "your vm name" $logfile = "log file name"
# 自定義日誌方法
Function LogWrite { Param ([string]$logstring) $now = Get-Date $logcontent = $now.ToShortDateString() + " " + $now.ToShortTimeString() + ": " + $logstring Add-Content $logfile -value $logcontent } LogWrite("before Select-AzureRmProfile.") Select-AzureRmProfile -Path $profile LogWrite("after Select-AzureRmProfile.") LogWrite("before Restart-AzureRmVM.") Restart-AzureRmVM -ResourceGroupName $resourceGroupName -Name $vmName LogWrite("after Restart-AzureRmVM.")
好了,一個簡單的自動化重啓工做就完成了!