在 Azure PowerShell 中使用指令碼建立 Azure 資源

已完成

互動模式中,PowerShell 可讓您撰寫命令並立即加以執行。

請記得客戶關係管理 (CRM) 範例的整體目標是要建立包含虛擬機器的三個測試環境。 您使用資源群組來確保 VM 會組織成不同的環境:一個用於單元測試、一個用於整合測試,還有一個則用於驗收測試。 您只需要建立資源群組一次,所以在此使用案例中使用 PowerShell 互動模式是不錯的選擇。

當您將命令輸入至 PowerShell 時,PowerShell 會比對此命令與 Cmdlet,然後執行要求的動作。 首先,我們會觀察您可使用的一些常用命令,然後討論如何安裝適用於 PowerShell 的 Azure 支援。

什麼是 PowerShell Cmdlet?

PowerShell 命令稱為 Cmdlet (發音為 "command-let")。 Cmdlet 是可操作單一功能的命令。 Cmdlet一詞旨在表示「小型命令」。依照慣例,Cmdlet 作者最好讓 Cmdlet 保持簡單且用途單純。

基底 PowerShell 產品隨附 cmdlet,其適用於工作階段和背景作業等功能。 您可以將課程模組新增至您的 PowerShell 安裝,以取得可操作其他功能的 Cmdlet。 例如,有第三方課程模組可使用 ftp、管理您的作業系統、存取檔案系統等等。

Cmdlet 會遵循動詞-名詞命名慣例,例如 Get-ProcessFormat-TableStart-Service。 另外還有動詞選擇慣例:"get" 用以擷取資料、"set" 用以插入或更新資料、"format" 用以將資料格式化、"out" 用以將輸出導向目的地等等。

Cmdlet 作者最好能針對每個 cmdlet 包含一個說明檔。 Get-Help Cmdlet 會顯示任何 Cmdlet 的說明檔。 例如,若要取得 Get-ChildItem Cmdlet 的說明,請在 Windows PowerShell 工作階段中輸入下列陳述式:

Get-Help -Name Get-ChildItem -Detailed

什麼是 PowerShell 課程模組?

Cmdlet 會隨附於模組中。 PowerShell 模組是一個動態連結程式庫 (DLL),其中包含可用來處理每個可用 Cmdlet 的程式碼。 您可將內含 Cmdlet 的模組載入,以將 Cmdlet 載入到 PowerShell 中。 您可以使用 Get-Module 命令取得已載入的模組清單:

Get-Module

此命令輸出如下:

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con...
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Binary     1.0.0.1    PackageManagement                   {Find-Package, Find-PackageProvider, Get-Package, Get-Pack...
Script     1.0.0.1    PowerShellGet                       {Find-Command, Find-DscResource, Find-Module, Find-RoleCap...
Script     2.0.0      PSReadline                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PS...

什麼是 Az PowerShell 模組?

Az 是 Azure PowerShell 模組的正式名稱,該模組包含可使用 Azure 功能的 Cmdlet。 它包含數百個 Cmdlet,可讓您幾乎控制每個 Azure 資源的各個層面。 您可以使用資源群組、儲存體、虛擬機器、Microsoft Entra ID、容器、機器學習等等。 Az 模組是可在 GitHub 上取得的開放原始碼元件。

注意

您可能已看過或使用過使用 -AzureRM 格式的 Azure PowerShell 命令。 由於 Az PowerShell 模組現在具備 AzureRM PowerShell 模組的所有功能,因此我們將於 2024 年 2 月 29 日淘汰 AzureRM PowerShell 模組。 若要避免服務中斷,請在 2024 年 2 月 29 日之前,將使用 AzureRM PowerShell 模組的指令碼更新為使用 Az PowerShell 模組。 若要自動更新您的指令碼,請遵循快速入門指南

安裝 Az PowerShell 模組

Az PowerShell 模組可從稱為「PowerShell 資源庫」的全域存放庫中取得。 您可以透過 Install-Module Cmdlet 將此模組安裝到本機電腦上。

若要安裝最新的 Azure Az PowerShell 模組,請執行下列命令:

  1. 開啟 [開始] 功能表,並輸入 PowerShell

  2. 選取 [PowerShell] 圖示。

  3. 輸入下列命令並按 Enter

    Install-Module -Name Az -Scope CurrentUser -Repository PSGallery
    

上述命令會為目前使用者安裝模組 (由 Scope 參數控制)。

此命令依賴 NuGet 來擷取元件。 因此,根據您安裝的版本而定,系統可能提示您下載並安裝最新版的 NuGet。

NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet
 provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\<username>\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running
'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install and import
 the NuGet provider now?
 [Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"):

輸入 Y,然後按 Enter

根據預設,不會將 PowerShell 資源庫設為 PowerShellGet 的信任存放庫。 每次從不受信任的存放庫執行安裝時,系統都會提示您確認您想要安裝具有下列輸出的模組:

You are installing the modules from an untrusted repository. If you trust this repository, change its
InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from
'PSGallery'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"):

輸入 YA,然後按 Enter

指令碼執行失敗

根據您的安全性設定,Import-Module 可能會失敗並產生如下的輸出:

import-module : File C:\Program Files\PowerShell\Modules\az\6.3.0\Az.psm1 cannot be loaded
because running scripts is disabled on this system. For more information, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ import-module Az
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [Import-Module], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand

其也可能因為完全沒有回應而失敗。 在此情況下,請按 Ctrl+C 來停止程式。

這兩種行為通常表示執行原則為 "Restricted," (受限),意味著您無法執行從外部來源下載的模組,包括 PowerShell 資源庫。 您可執行 Get-ExecutionPolicy Cmdlet 來檢查。 如果 Cmdlet 傳回 「Restricted,」,則:

  1. 使用 Set-ExecutionPolicy Cmdlet 將原則變更為 "RemoteSigned":

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
    

    系統會提示您授與權限:

    The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
    you to the security risks described in the about_Execution_Policies help topic at
    https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
    [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): Y
    
  2. 輸入 YA,然後按 Enter

  3. 在命令提示字元,使用鍵盤上的向上箭號,然後重新執行適用於 Azure 的 Install-Module 命令。

您應該能夠看到 Az PowerShell 模組載入。 完成之後,您就能夠使用 Import-Module 來載入 Cmdlet。

在 Linux 或 macOS 上安裝 Azure PowerShell 時,使用相同的命令。

  1. 在終端中,執行下列命令以啟動 PowerShell。

    pwsh
    
  2. 在 PowerShell 提示字元執行下列命令以安裝 Azure PowerShell。

    Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force
    
  3. 如果詢問您是否信任來自 PSGallery 的模組,請回答 [是] 或 [全部皆是]

更新 PowerShell 模組

您可能會收到警告或錯誤訊息,指出已安裝 Azure PowerShell 模組的版本。 如果是,您可以發出下列命令來更新為「最新」版本。

Update-Module -Name Az

如同 Install-Module Cmdlet,當系統提示詢問是否信任模組時,請回答 [是] 或 [全部皆是]。 如果執行時發生問題,您也可以使用 Update-Module 命令重新安裝模組。

範例:如何使用 Azure PowerShell 建立資源群組

安裝 Azure 模組後,即可開始使用 Azure。 我們現在要進行一項常見工作:建立資源群組。 如您所知,我們可以使用資源群組一併管理相關的資源。 開始使用新的 Azure 解決方案時,建立新的資源群組是您要執行的首要工作之一。

您必須執行四個步驟:

  1. 匯入 Azure Cmdlet。

  2. 連線至 Azure 訂用帳戶。

  3. 建立資源群組。

  4. 驗證是否已成功建立。

下圖說明這些步驟的概觀:

Diagram showing the steps to create a resource group.

每個步驟各對應至不同的 Cmdlet。

匯入 Azure Cmdlet

從 PowerShell 3.0 開始,當您在模組內使用 Cmdlet 時會自動載入模組。 除非您已變更預設模組自動載入設定,否則不再需要手動匯入 PowerShell 模組。

連線

當您使用 Azure PowerShell 的本機安裝時,您必須先進行驗證,才能執行 Azure 命令。 Connect-AzAccount Cmdlet 會提示您輸入 Azure 認證,然後連線至您的 Azure 訂用帳戶。 它有許多選用參數,但如果您只需要互動式提示,則不需要任何參數:

Connect-AzAccount

使用訂用帳戶

如果您是 Azure 的新手,可能只會擁有單一訂用帳戶。 然而,如果您已使用 Azure 一段時間,則可能已建立多個 Azure 訂用帳戶。 您可以將 Azure PowerShell 設定為針對特定訂用帳戶執行命令。

您一次只能進入一個訂用帳戶。 使用 Get-AzContext Cmdlet 來判斷哪個是作用中的訂用帳戶。 如果不是正確的訂用帳戶,您可使用另一個 Cmdlet 來變更訂用帳戶。

  1. 使用 Get-AzSubscription 命令,取得您帳戶中所有訂用帳戶名稱的清單。

  2. 傳入所要選取的訂用帳戶名稱,以變更訂用帳戶。

Set-AzContext -Subscription '00000000-0000-0000-0000-000000000000'

如果您需要查閱 [訂用帳戶識別碼],移至 Azure 入口網站,然後在首頁上選取 [訂用帳戶]。

取得所有資源群組的清單

您可以擷取使用中訂用帳戶內所有資源群組的清單。

Get-AzResourceGroup

若要取得更精確的檢視,您可以使用直線符號 '|',將 Get-AzResourceGroup 的輸出傳送至 Format-Table Cmdlet。

Get-AzResourceGroup | Format-Table

輸出會與下列內容類似:

ResourceGroupName                  Location       ProvisioningState Tags TagsTable ResourceId
-----------------                  --------       ----------------- ---- --------- ----------
cloud-shell-storage-southcentralus southcentralus Succeeded                        /subscriptions/00000000-0000-0000...
ExerciseResources                  eastus         Succeeded                        /subscriptions/00000000-0000-0000...

建立資源群組

如您所知,當您在 Azure 中建立資源時,一律會將其放在資源群組中,以便進行管理。 開始使用新的應用程式時,資源群組通常是您最先建立的項目之一。

您可使用 New-AzResourceGroup Cmdlet 來建立資源群組。 您必須指定名稱和位置。 名稱在您的訂用帳戶內必須是唯一。 位置會決定資源群組中繼資料的儲存位置 (基於合規性理由,這對您可能很重要)。 您可以使用 "West US"、"North Europe" 或 "West India" 這類字串來指定位置。 如同大多數的 Azure Cmdlet,New-AzResourceGroup 有許多選用參數。 不過,核心語法為:

New-AzResourceGroup -Name <name> -Location <location>

注意

請記住,我們將在為您建立資源群組的使用中 Azure 沙箱內操作。 如果您偏好在自己的訂用帳戶中工作,請使用先前的命令。

確認資源

Get-AzResource 會列出您的 Azure 資源,這在此有助於驗證已建立資源以及資源群組建立已成功。

Get-AzResource

如同 Get-AzResourceGroup 命令,您可以透過 Format-Table Cmdlet 取得更精確的檢視:

Get-AzResource | Format-Table

您也可以將其篩選為特定資源群組,而僅列出與該群組相關聯的資源:

Get-AzResource -ResourceGroupName ExerciseResources

建立 Azure 虛擬機器

您可以使用 PowerShell 執行的另一項常見工作是建立 VM。

Azure PowerShell 所提供的 New-AzVm Cmdlet 可用來建立虛擬機器。 此 Cmdlet 有許多參數可讓其處理大量的 VM 組態設定。 大多數參數都有合理的預設值,因此我們只需要指定五個參數:

  • ResourceGroupName:應用於放置新 VM 的資源群組。
  • Name:Azure 中 VM 的名稱。
  • Location:應用來佈建 VM 的地理位置。
  • Credential:含有 VM 系統管理員帳戶使用者名稱和密碼的物件。 我們會使用 Get-Credential Cmdlet。 此 Cmdlet 會提示您輸入使用者名稱和密碼,並將其封裝到認證物件中。
  • Image:要使用於 VM 的作業系統映像,通常是 Linux 發行版本或 Windows Server。
   New-AzVm
       -ResourceGroupName <resource group name>
       -Name <machine name>
       -Credential <credentials object>
       -Location <location>
       -Image <image name>

您可以將這些參數直接提供給 Cmdlet,如先前範例中所示。 或者,您可使用其他 Cmdlet 來設定虛擬機器,例如 Set-AzVMOperatingSystemSet-AzVMSourceImageAdd-AzVMNetworkInterfaceSet-AzVMOSDisk

以下是將 Get-Credential Cmdlet 與 -Credential 參數搭配使用的範例:

New-AzVM -Name MyVm -ResourceGroupName ExerciseResources -Credential (Get-Credential) ...

AzVM 是 PowerShell 中 VM 型命令專用的尾碼。 您還可以使用其他數個項目:

Command 描述
Remove-AzVM 刪除 Azure VM
Start-AzVM 啟動已停止的 VM
Stop-AzVM 停止執行中 VM
Restart-AzVM 重新啟動 VM
Update-AzVM 更新 VM 的設定

範例:取得虛擬機器的資訊

您可以使用 Get-AzVM -Status 命令列出您訂用帳戶中的 VM。 此命令也支援藉由包含 -Name 屬性來輸入特定 VM。 在此處,我們會將其指派給 PowerShell 變數:

$vm = Get-AzVM  -Name MyVM -ResourceGroupName ExerciseResources

有趣的是,您的 VM 現在是您可與其互動的「物件」。 例如,您可以對該物件進行變更,然後使用 Update-AzVM 命令將變更推送回 Azure:

$ResourceGroupName = "ExerciseResources"
$vm = Get-AzVM  -Name MyVM -ResourceGroupName $ResourceGroupName
$vm.HardwareProfile.vmSize = "Standard_DS3_v2"

Update-AzVM -ResourceGroupName $ResourceGroupName  -VM $vm

PowerShell 的互動模式適合用於一次性工作。 在我們的範例中,我們會在專案的存留期中使用相同的資源群組,因此以互動方式建立很合理。 相較於撰寫指令碼且僅只執行該指令碼一次,互動模式通常可讓此工作更快速且輕鬆地執行。