How to create a VM in PowerShell?

# Define a credential object
$cred = Get-Credential
# Create a virtual machine configuration
$vmConfig = New-AzureRmVMConfig -VMName myVM -VMSize Standard_DS2 |
` Set-AzureRmVMOperatingSystem -Windows -ComputerName myVM -Credential $cred |
` Set-AzureRmVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer `
-Skus 2016-Datacenter -Version latest | Add-AzureRmVMNetworkInterface -Id $nic.Id

 

To create a virtual machine (VM) in Microsoft Azure using PowerShell, you can follow these steps:

  1. Open PowerShell: Open the PowerShell command prompt or the PowerShell Integrated Scripting Environment (ISE).
  2. Install and Import Azure PowerShell Module (if not already installed):
    powershell

 

  • Install-Module -Name Az -AllowClobber -Force -Scope CurrentUser
    Import-Module Az
  • Authenticate to your Azure account:
    powershell
  • Connect-AzAccount

    Follow the prompts to sign in with your Azure credentials.

  • Select your Azure subscription (if you have multiple subscriptions):
    powershell
  • Set-AzContext -SubscriptionId <SubscriptionId>

    Replace <SubscriptionId> with your actual subscription ID.

  • Define variables for VM configuration (modify as needed):
    powershell
  • $resourceGroupName = "YourResourceGroup"
    $location = "YourLocation" # e.g., East US
    $vmName = "YourVMName"
    $adminUsername = "YourAdminUsername"
    $adminPassword = "YourAdminPassword" # Use secure methods for handling passwords in production
  • Create a new VM configuration:
    powershell
  • $vmConfig = New-AzVMConfig -VMName $vmName -VMSize "Standard_DS2_v2"
    $vmConfig = Set-AzVMOperatingSystem -VM $vmConfig -Windows -ComputerName $vmName -Credential (Get-Credential -UserName $adminUsername -Password $adminPassword)
  • Choose an OS image (Windows or Linux) and create the VM:
    • For Windows:
      powershell
  • $vmConfig = Set-AzVMSourceImage -VM $vmConfig -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2019-Datacenter -Version latest
  • For Linux (Ubuntu example):
    powershell
    • $vmConfig = Set-AzVMSourceImage -VM $vmConfig -PublisherName Canonical -Offer UbuntuServer -Skus 18.04-LTS -Version latest
  • Specify other VM configurations (e.g., networking, storage):
    powershell
  • $vmConfig = Add-AzVMNetworkInterface -VM $vmConfig -Id <NICResourceId>
    $vmConfig = Set-AzVMOSDisk -VM $vmConfig -Name "osdisk" -CreateOption fromImage -Caching ReadWrite

    Replace <NICResourceId> with the actual network interface card (NIC) resource ID.

  • Create the VM:
    powershell

 

  1. New-AzVM -ResourceGroupName $resourceGroupName -Location $location -VM $vmConfig -Verbose

Replace the placeholder values with your actual information, and customize the script according to your specific requirements.