Using PowerShell in Azure to assign a new virtual machine to an existing virtual network!

MVP

 

Hi Azure friends,

 

I used the PowerShell ISE for this configuration. But you are also very welcome to use Visual Studio Code, just as you wish. Please start with the following steps to begin the deployment (the Hashtags are comments):

 

#The first two lines have nothing to do with the configuration, but make some space below in the blue part of the ISE

Set-Location C:\Temp
Clear-Host

 

#So that you can carry out the configuration, you need the necessary cmdlets, these are contained in the module Az (is the higher-level module from a number of submodules)

Install-Module -Name Az -Force -AllowClobber -Verbose

 

#Log into Azure
Connect-AzAccount

 

#Search for the resource groups
Get-AzResourceGroup | Format-Table

#Whats in a specific resource group
Get-AzResource -ResourceGroupName tw-azuredemo-rg | Format-Table

#Some variables
$RGName = "tw-azuredemo-rg"
$VnetName = "tw-vnet-workload"
$Location = "westeurope"
$VMName = "twsrv2021"
$credential = Get-Credential

#We need all infos about the virtual network
$VirtualNetwork = (Get-AzVirtualNetwork -Name $VnetName -ResourceGroupName $RGName)

#Let's have a look at the variable
$VirtualNetwork

#Create a network interface
$nic = New-AzNetworkInterface `
    -ResourceGroupName $RGName `
    -Name "twsrv2021-nic" `
    -Location $Location `
    -SubnetId $VirtualNetwork.Subnets[0].Id

#Define your VM
$vmConfig = New-AzVMConfig -VMName $VMName -VMSize "Standard_D2s_v4"

#Create the rest of your VM configuration
$vmConfig = Set-AzVMOperatingSystem -VM $vmConfig `
    -Windows `
    -ComputerName $VMName `
    -Credential $credential `
    -ProvisionVMAgent `
    -EnableAutoUpdate
$vmConfig = Set-AzVMSourceImage -VM $vmConfig `
    -PublisherName "MicrosoftWindowsServer" `
    -Offer "WindowsServer" `
    -Skus "2016-Datacenter" `
    -Version "latest"

#Attach the network interface that you previously created
$vmConfig = Add-AzVMNetworkInterface -VM $vmConfig -Id $nic.Id

#Create your VM
New-AzVM -VM $vmConfig -ResourceGroupName $RGName -Location $Location

 

Now you have used the PowerShell to create a new virtual machine and added to an existing virtual network! Congratulations!
 

I hope this article was useful. Best regards, Tom Wechsler

 

P.S. All scripts (#PowerShell, Azure CLI, #Terraform, #ARM) that I use can be found on github! https://github.com/tomwechsler

0 Replies