1
votes

I'm trying to create an Azure VM using PowerShell. I'm able to successfully create one, but the problem I have is that I'm trying to get the new VM to use an existing VNET and Subnet in a different resource group. When I run my code, it tries to create a brand new VNET and Subnet. I don't know how to link it to use the existing VNET which resides in a different resource group.

# Define Local Variables
$RG = "TestLab"
$Location = "eastus"
$UserName = "azadmin"
$Password = (ConvertTo-SecureString "Passw0rd123!" -Force -AsPlainText)
$VMName = "TestBox-VM-PS"
$VMSize = "Standard_D2as_V4"
$VirtualNetwork = "azTestBox01_vnet" #existing Vnet on different resource group
$Subnet = "TestBOX-Sub-10.0.0.0" #existing subnet on different resource group
$Friendly_Image_Name = "MicrosoftWindowsServer:WindowsServer:2019-Datacenter:Latest"


# Set credentials
$Credential = New-Object System.Management.Automation.PSCredential ($UserName, $Password)

New-AzVm `
-Name $VMName `
-ResourceGroupName $RG `
-Location $Location `
-VirtualNetworkName $VirtualNetwork `
-SubnetName $Subnet `
-Image $Friendly_Image_Name `
-Size $VMSize `
-Credential $Credential
1

1 Answers

0
votes

Unfortunately the New-AzVM cmdlet does not allow you to specify the resource group of the vnet that you want to connect your VM to. It will always assume that the vnet resides in the same resource group as the one to which the VM is deployed.

You can work around this by creating the configuration for your VM step by step:

# Define Local Variables
$RG = "TestLab"
$Location = "westeurope"

$UserName = "azadmin"
$Password = (ConvertTo-SecureString "Passw0rd123!" -Force -AsPlainText)
$VMName = "TestBox-VM-PS"
$Credential = New-Object System.Management.Automation.PSCredential ($UserName, $Password)

$publisherName = "MicrosoftWindowsServer"
$offer = "WindowsServer"
$sku = "2019-Datacenter"
$version = "Latest"
$vNicName = "NetworkInterface1"

$VirtualNetwork = "azTestBox01_vnet" #existing Vnet on different resource group
$Subnet = "TestBOX-Sub-10.0.0.0" #existing subnet on different resource group
$vnetResourceGroupName = "TestLabVnet" #resource group of the existing subnet

New-AzResourceGroup -Name $RG -Location $Location
$vNet = Get-AzVirtualNetwork -Name $VirtualNetwork -ResourceGroupName $vnetResourceGroupName
$subnetId = $vNet.Subnets | Where-Object Name -eq $Subnet | Select-Object -ExpandProperty Id
$vNic = New-AzNetworkInterface -Name $vNicName -ResourceGroupName $RG -Location $Location -SubnetId $subnetId
$vm = New-AzVMConfig -VMName $VMName -VMSize $VMSize
$vm = Set-AzVMOperatingSystem -VM $vm -Windows -ComputerName $VMName -Credential $Credential -ProvisionVMAgent -EnableAutoUpdate
$vm = Add-AzVMNetworkInterface -VM $vm -Id $vNic.Id
$vm = Set-AzVMSourceImage -VM $vm -PublisherName $publisherName -Offer $offer -Skus $sku -Version $version
New-AzVM -ResourceGroupName $RG -Location $Location -VM $vm -Verbose