Create a Windows Server Virtual Machine in Microsoft Azure using PowerShell script

Change the following values as per your preference

  • username
  • password
  • Resource Group Name (Resource Group must be pre-existed before starting the script)

The script is able to create a Windows 2019 Datacenter server and prepares a security group so that you can access the computer through RDP

$vmAdminUsername = "Enter UserName"
$vmAdminPassword = ConvertTo-SecureString "Enter strong Password" -AsPlainText -Force
$vmComputerName = "WIN2K19"
$azureLocation  = "EastUS"
$azureResourceGroup = "Enter Resource Group Name"
$azureVmName  = "WIN2K19"
$azureVmSize  = "Standard_D2s_v3"
$azureVmPublisherName = "MicrosoftWindowsServer"
$azureVmOffer = "WindowsServer"
$azureVmSkus = "2019-Datacenter"
$NetworkName = "MyNet"
$NICName = "MyNIC"
$SubnetName = "MySubnet"
$azurePublicIpName = "MyPublicIP"
$SubnetAddressPrefix = "10.0.0.0/24"
$VnetAddressPrefix = "10.0.0.0/16"
$NSGName = "MyNSG"
$azurePublicIp = New-AzPublicIpAddress -Name $azurePublicIpName -ResourceGroupName $azureResourceGroup -Location $azureLocation -AllocationMethod Dynamic
$SingleSubnet = New-AzVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetAddressPrefix
$Vnet = New-AzVirtualNetwork -Name $NetworkName -ResourceGroupName $azureResourceGroup -Location $azureLocation -AddressPrefix $VnetAddressPrefix -Subnet $SingleSubnet
$nsgRuleRDP = New-AzNetworkSecurityRuleConfig -Name RDP  -Protocol Tcp  -Direction Inbound -Priority 1001 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 3389 -Access Allow;
$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $azureResourceGroup -Location $azureLocation -Name $NSGName  -SecurityRules $nsgRuleRDP;
$NIC = New-AzNetworkInterface -Name $NICName -ResourceGroupName $azureResourceGroup -Location $azureLocation -SubnetId $Vnet.Subnets[0].Id -PublicIpAddressId $azurePublicIp.Id -NetworkSecurityGroupId $nsg.Id
$vmCredential = New-Object System.Management.Automation.PSCredential ($vmAdminUsername, $vmAdminPassword)
$VirtualMachine = New-AzVMConfig -VMName $azureVmName -VMSize $azureVmSize
$VirtualMachine = Set-AzVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName $vmComputerName -Credential $vmCredential
$VirtualMachine = Add-AzVMNetworkInterface -VM $VirtualMachine -Id $NIC.Id
$VirtualMachine = Set-AzVMSourceImage -VM $VirtualMachine -PublisherName $azureVmPublisherName -Offer $azureVmOffer -Skus $azureVmSkus -Version "latest"
$VirtualMachine = Set-AzVMBootDiagnostic -VM $VirtualMachine -Disable
$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -StorageAccountType "StandardSSD_LRS" -CreateOption FromImage
New-AzVM -ResourceGroupName $azureResourceGroup -Location $azureLocation -VM $VirtualMachine -Verbose

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Comments
Add External Contacts in Microsoft Teams