教學課程:使用 Azure PowerShell 建立和管理 Windows VMTutorial: Create and Manage Windows VMs with Azure PowerShell

Azure 虛擬機器提供完全可設定且彈性的計算環境。Azure virtual machines provide a fully configurable and flexible computing environment. 本教學課程將說明基本的 Azure 虛擬機器 (VM) 部署工作,例如選取 VM 大小、選取 VM 映像、部署 VM。This tutorial covers basic Azure virtual machine (VM) deployment tasks like selecting a VM size, selecting a VM image, and deploying a VM. 您會了解如何:You learn how to:

  • 建立及連線到 VMCreate and connect to a VM
  • 選取及使用 VM 映像Select and use VM images
  • 檢視及使用特定 VM 大小View and use specific VM sizes
  • 調整 VM 的大小Resize a VM
  • 檢視及了解 VM 狀態View and understand VM state

啟動 Azure Cloud ShellLaunch Azure Cloud Shell

Azure Cloud Shell 是免費的互動式 Shell,可讓您用來執行本文中的步驟。The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. 它具有預先安裝和設定的共用 Azure 工具,可與您的帳戶搭配使用。It has common Azure tools preinstalled and configured to use with your account.

若要開啟 Cloud Shell,只要選取程式碼區塊右上角的 [試試看] 即可。To open the Cloud Shell, just select Try it from the upper right corner of a code block. 您也可以移至 https://shell.azure.com/powershell,從另一個瀏覽器索引標籤啟動 Cloud Shell。You can also launch Cloud Shell in a separate browser tab by going to https://shell.azure.com/powershell. 選取 [複製] 即可複製程式碼區塊,將它貼到 Cloud Shell 中,然後按 enter 鍵加以執行。Select Copy to copy the blocks of code, paste it into the Cloud Shell, and press enter to run it.

建立資源群組Create resource group

使用 New-AzResourceGroup 命令來建立資源群組。Create a resource group with the New-AzResourceGroup command.

Azure 資源群組是在其中部署與管理 Azure 資源的邏輯容器。An Azure resource group is a logical container into which Azure resources are deployed and managed. 資源群組必須在虛擬機器之前建立。A resource group must be created before a virtual machine. 在下列範例中,會在 EastUS 區域中建立名為 myResourceGroupVM 的資源群組:In the following example, a resource group named myResourceGroupVM is created in the EastUS region:

New-AzResourceGroup `
   -ResourceGroupName "myResourceGroupVM" `
   -Location "EastUS"

在建立或修改 VM 時,會指定資源群組,在本教學課程的整個過程中可以看到此操作。The resource group is specified when creating or modifying a VM, which can be seen throughout this tutorial.

建立 VMCreate a VM

建立 VM 時,有數個選項可供使用,例如作業系統映像、網路組態和系統管理認證。When creating a VM, several options are available like operating system image, network configuration, and administrative credentials. 此範例會執行 Windows Server 2016 Datacenter 的預設版本,建立名為 myVM 的 VM。This example creates a VM named myVM, running the default version of Windows Server 2016 Datacenter.

使用 Get-Credential 來設定 VM 上系統管理員帳戶所需的使用者名稱和密碼:Set the username and password needed for the administrator account on the VM with Get-Credential:

$cred = Get-Credential

使用 New-AzVM 建立 VM。Create the VM with New-AzVM.

New-AzVm `
    -ResourceGroupName "myResourceGroupVM" `
    -Name "myVM" `
    -Location "EastUS" `
    -VirtualNetworkName "myVnet" `
    -SubnetName "mySubnet" `
    -SecurityGroupName "myNetworkSecurityGroup" `
    -PublicIpAddressName "myPublicIpAddress" `
    -Credential $cred

連接到 VMConnect to VM

完成部署之後,請建立 VM 的遠端桌面連線。After the deployment has completed, create a remote desktop connection with the VM.

執行下列命令,以傳回 VM 的公用 IP 位址。Run the following commands to return the public IP address of the VM. 記下這個 IP 位址,您便可以使用瀏覽器進行連線,以在未來步驟中測試 Web 連線能力。Take note of this IP Address so you can connect to it with your browser to test web connectivity in a future step.

Get-AzPublicIpAddress `
   -ResourceGroupName "myResourceGroupVM"  | Select IpAddress

在本機電腦上使用下列命令,建立 VM 的遠端桌面工作階段。Use the following command, on your local machine, to create a remote desktop session with the VM. 請將 IP 位址取代為 VM 的 publicIPAddress 。Replace the IP address with the publicIPAddress of your VM. 出現提示時,請輸入您在建立 VM 時所使用的認證。When prompted, enter the credentials used when creating the VM.

mstsc /v:<publicIpAddress>

在 [Windows 安全性] 視窗中,選取 [更多選擇] ,然後選取 [使用不同的帳戶] 。In the Windows Security window, select More choices and then Use a different account. 輸入您為 VM 建立的使用者名稱和密碼,然後按一下 [確定] 。Type the username and password you created for the VM and then click OK.

了解 Marketplace 映像Understand marketplace images

Azure Marketplace 包含許多可用來建立新 VM 的映像。The Azure marketplace includes many images that can be used to create a new VM. 在先前步驟中,已使用 Windows Server 2016 Datacenter 映像建立 VM。In the previous steps, a VM was created using the Windows Server 2016 Datacenter image. 在此步驟中,PowerShell 模組用來搜尋 Marketplace 中的其他 Windows 映像,其也可用來作為新 VM 的基底。In this step, the PowerShell module is used to search the marketplace for other Windows images, which can also be used as a base for new VMs. 這個程序包含尋找發行者、供應項目、SKU 和版本號碼 (選擇性) 來識別映像。This process consists of finding the publisher, offer, SKU, and optionally a version number to identify the image.

使用 Get-AzVMImagePublisher 命令傳回映像發行者清單:Use the Get-AzVMImagePublisher command to return a list of image publishers:

Get-AzVMImagePublisher -Location "EastUS"

使用 Get-AzVMImageOffer 傳回映像提供清單。Use the Get-AzVMImageOffer to return a list of image offers. 使用此命令時,會根據名為 MicrosoftWindowsServer 的指定發行者篩選傳回的清單:With this command, the returned list is filtered on the specified publisher named MicrosoftWindowsServer:

Get-AzVMImageOffer `
   -Location "EastUS" `
   -PublisherName "MicrosoftWindowsServer"

結果將如下列範例所示:The results will look something like this example:

Offer             PublisherName          Location
-----             -------------          --------
Windows-HUB       MicrosoftWindowsServer EastUS
WindowsServer     MicrosoftWindowsServer EastUS
WindowsServer-HUB MicrosoftWindowsServer EastUS

Get-AzVMImageSku 命令會接著根據發行者和供應項目名稱篩選,以傳回映像名稱清單。The Get-AzVMImageSku command will then filter on the publisher and offer name to return a list of image names.

Get-AzVMImageSku `
   -Location "EastUS" `
   -PublisherName "MicrosoftWindowsServer" `
   -Offer "WindowsServer"

結果將如下列範例所示:The results will look something like this example:

Skus                                      Offer         PublisherName          Location
----                                      -----         -------------          --------
2008-R2-SP1                               WindowsServer MicrosoftWindowsServer EastUS  
2008-R2-SP1-smalldisk                     WindowsServer MicrosoftWindowsServer EastUS  
2012-Datacenter                           WindowsServer MicrosoftWindowsServer EastUS  
2012-Datacenter-smalldisk                 WindowsServer MicrosoftWindowsServer EastUS  
2012-R2-Datacenter                        WindowsServer MicrosoftWindowsServer EastUS  
2012-R2-Datacenter-smalldisk              WindowsServer MicrosoftWindowsServer EastUS  
2016-Datacenter                           WindowsServer MicrosoftWindowsServer EastUS  
2016-Datacenter-Server-Core               WindowsServer MicrosoftWindowsServer EastUS  
2016-Datacenter-Server-Core-smalldisk     WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-smalldisk                 WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-with-Containers           WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-with-Containers-smalldisk WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-with-RDSH                 WindowsServer MicrosoftWindowsServer EastUS
2016-Nano-Server                          WindowsServer MicrosoftWindowsServer EastUS

此資訊可用來以特定映像部署 VM。This information can be used to deploy a VM with a specific image. 此範例會使用最新版的 Windows Server 2016 with Containers 映像部署 VM。This example deploys a VM using the latest version of a Windows Server 2016 with Containers image.

New-AzVm `
    -ResourceGroupName "myResourceGroupVM" `
    -Name "myVM2" `
    -Location "EastUS" `
    -VirtualNetworkName "myVnet" `
    -SubnetName "mySubnet" `
    -SecurityGroupName "myNetworkSecurityGroup" `
    -PublicIpAddressName "myPublicIpAddress2" `
    -ImageName "MicrosoftWindowsServer:WindowsServer:2016-Datacenter-with-Containers:latest" `
    -Credential $cred `
    -AsJob

-AsJob 參數會以背景工作建立 VM,因此會傳回 PowerShell 提示。The -AsJob parameter creates the VM as a background task, so the PowerShell prompts return to you. 您可以使用 Get-Job Cmdlet 檢視背景作業的詳細資料。You can view details of background jobs with the Get-Job cmdlet.

了解 VM 大小Understand VM sizes

VM 大小會決定可供 VM 使用的計算資源 (例如 CPU、GPU 和記憶體) 數量。The VM size determines the amount of compute resources like CPU, GPU, and memory that are made available to the VM. 虛擬機器必須適用於工作負載的 VM 大小來建立。Virtual machines should be created using a VM size appropriate for the workload. 如果工作負載增加,可以調整現有虛擬機器的大小。If a workload increases, an existing virtual machine can also be resized.

VM 大小VM Sizes

下表會將大小分類成各種使用案例。The following table categorizes sizes into use cases.

類型Type 一般大小Common sizes 描述Description
一般用途General purpose B, Dsv3, Dv3, DSv2, Dv2, Av2, DCB, Dsv3, Dv3, DSv2, Dv2, Av2, DC 平衡的 CPU 對記憶體。Balanced CPU-to-memory. 適用於開發/測試及小型到中型應用程式和資料解決方案。Ideal for dev / test and small to medium applications and data solutions.
計算最佳化Compute optimized Fsv2Fsv2 CPU 與記憶體的比例高。High CPU-to-memory. 適用於中流量應用程式、網路設備,以及批次處理。Good for medium traffic applications, network appliances, and batch processes.
記憶體最佳化Memory optimized Esv3、Ev3、M、DSv2、Dv2Esv3, Ev3, M, DSv2, Dv2 記憶體與核心的比例高。High memory-to-core. 適用於關聯式資料庫、中型到大型快取,以及記憶體內分析。Great for relational databases, medium to large caches, and in-memory analytics.
儲存體最佳化Storage optimized Lsv2、LsLsv2, Ls 高磁碟輸送量及 IO。High disk throughput and IO. 適用於巨量資料、SQL 及 NoSQL 資料庫。Ideal for Big Data, SQL, and NoSQL databases.
GPUGPU NV、NVv2、NC、NCv2、NCv3、NDNV, NVv2, NC, NCv2, NCv3, ND 以大量圖形轉譯和視訊編輯為目標的特製化 VM。Specialized VMs targeted for heavy graphic rendering and video editing.
高效能High performance HH 我們的最強大 CPU VM,可搭配選用的高輸送量網路介面 (RDMA)。Our most powerful CPU VMs with optional high-throughput network interfaces (RDMA).

尋找可用的 VM 大小Find available VM sizes

若要查看特定區域中可用的 VM 大小清單,請使用 Get-AzVMSize 命令。To see a list of VM sizes available in a particular region, use the Get-AzVMSize command.

Get-AzVMSize -Location "EastUS"

調整 VM 的大小Resize a VM

在部署 VM 之後,可以調整其大小以增加或減少資源配置。After a VM has been deployed, it can be resized to increase or decrease resource allocation.

在調整 VM 的大小之前,請檢查目前的 VM 叢集上是否有您所要的大小。Before resizing a VM, check if the size you want is available on the current VM cluster. Get-AzVMSize 命令會傳回大小清單。The Get-AzVMSize command returns a list of sizes.

Get-AzVMSize -ResourceGroupName "myResourceGroupVM" -VMName "myVM"

如果此大小可用,即可從已開機狀態調整 VM 的大小,但是會在作業期間重新開機。If the size is available, the VM can be resized from a powered-on state, however it is rebooted during the operation.

$vm = Get-AzVM `
   -ResourceGroupName "myResourceGroupVM"  `
   -VMName "myVM"
$vm.HardwareProfile.VmSize = "Standard_DS3_v2"
Update-AzVM `
   -VM $vm `
   -ResourceGroupName "myResourceGroupVM"

如果目前的叢集上沒有您所需的大小,則必須先將 VM 解除配置,才能進行調整大小的作業。If the size you want isn't available on the current cluster, the VM needs to be deallocated before the resize operation can occur. 將 VM 解除配置後,暫存磁碟上的所有資料都會移除,且公用 IP 位址將會變更,除非正在使用靜態 IP 位址。Deallocating a VM will remove any data on the temp disk, and the public IP address will change unless a static IP address is being used.

Stop-AzVM `
   -ResourceGroupName "myResourceGroupVM" `
   -Name "myVM" -Force
$vm = Get-AzVM `
   -ResourceGroupName "myResourceGroupVM"  `
   -VMName "myVM"
$vm.HardwareProfile.VmSize = "Standard_E2s_v3"
Update-AzVM -VM $vm `
   -ResourceGroupName "myResourceGroupVM"
Start-AzVM `
   -ResourceGroupName "myResourceGroupVM"  `
   -Name $vm.name

VM 電源狀態VM power states

Azure VM 的電源狀態可以是許多電源狀態的其中一種。An Azure VM can have one of many power states.

電源狀態Power State 描述Description
啟動中Starting 虛擬機器正在啟動。The virtual machine is being started.
執行中Running 虛擬機器未執行。The virtual machine is running.
停止中Stopping 虛擬機器正在停止。The virtual machine is being stopped.
已停止Stopped VM 已停止。The VM is stopped. 處於已停止狀態的虛擬機器仍然會產生運算費用。Virtual machines in the stopped state still incur compute charges.
正在解除配置Deallocating VM 正在解除配置。The VM is being deallocated.
已解除配置Deallocated 表示 VM 已從 Hypervisor 中移除,但仍可在控制平面中使用。Indicates that the VM is removed from the hypervisor but is still available in the control plane. 處於 Deallocated 狀態的虛擬機器不會產生計算費用。Virtual machines in the Deallocated state do not incur compute charges.
- VM 的電源狀態不明。The power state of the VM is unknown.

若要取得特定 VM 的狀態,請使用 Get-AzVM 命令。To get the state of a particular VM, use the Get-AzVM command. 請務必為 VM 和資源群組指定有效的名稱。Be sure to specify a valid name for a VM and resource group.

Get-AzVM `
    -ResourceGroupName "myResourceGroupVM" `
    -Name "myVM" `
    -Status | Select @{n="Status"; e={$_.Statuses[1].Code}}

輸出會如下列範例所示:The output will look something like this example:

Status
------
PowerState/running

若要取得訂用帳戶中所有 VM 的電源狀態,請使用虛擬機器 - 列出所有 API,並將參數 statusOnly 設定為 True。To retrieve the power state of all the VMs in your subscription, use the Virtual Machines - List All API with parameter statusOnly set to true.

管理工作Management tasks

在 VM 的生命週期內,您可能會執行一些管理工作,例如啟動、停止或刪除 VM。During the lifecycle of a VM, you may want to run management tasks like starting, stopping, or deleting a VM. 此外,您可以建立指令碼來自動執行重複或複雜的工作。Additionally, you may want to create scripts to automate repetitive or complex tasks. 使用 Azure PowerShell,可以從命令列或在指令碼中執行許多常見的管理工作。Using Azure PowerShell, many common management tasks can be run from the command line or in scripts.

停止 VMStop a VM

使用 Stop-AzVM 停止及解除配置 VM:Stop and deallocate a VM with Stop-AzVM:

Stop-AzVM `
   -ResourceGroupName "myResourceGroupVM" `
   -Name "myVM" -Force

如果您想要將 VM 保留在佈建狀態,請使用 -StayProvisioned 參數。If you want to keep the VM in a provisioned state, use the -StayProvisioned parameter.

啟動 VMStart a VM

Start-AzVM `
   -ResourceGroupName "myResourceGroupVM" `
   -Name "myVM"

刪除資源群組Delete resource group

當您刪除資源群組時,會刪除資源群組內的所有項目。Everything inside of a resource group is deleted when you delete the resource group.

Remove-AzResourceGroup `
   -Name "myResourceGroupVM" `
   -Force

後續步驟Next steps

在本教學課程中,您已了解基本的 VM 建立和管理,像是如何:In this tutorial, you learned about basic VM creation and management such as how to:

  • 建立及連線到 VMCreate and connect to a VM
  • 選取及使用 VM 映像Select and use VM images
  • 檢視及使用特定 VM 大小View and use specific VM sizes
  • 調整 VM 的大小Resize a VM
  • 檢視及了解 VM 狀態View and understand VM state

請前進到下一個教學課程,以了解 VM 磁碟。Advance to the next tutorial to learn about VM disks.