Aracılığıyla paylaş


Peer two virtual networks script sample

This script sample creates and connects two virtual networks in the same region through the Azure network. After running the script, you'll create a peering between two virtual networks.

You can execute the script from the Azure Cloud Shell, or from a local PowerShell installation. If you use PowerShell locally, this script requires the Az PowerShell module version 5.4.1 or later. To find the installed version, run Get-Module -ListAvailable Az. If you need to upgrade, see Install Azure PowerShell module. If you're running PowerShell locally, you also need to run Connect-AzAccount to create a connection with Azure.

If you don't have an Azure subscription, create an Azure free account before you begin.

Sample script

Note

We recommend that you use the Azure Az PowerShell module to interact with Azure. To get started, see Install Azure PowerShell. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

# Variables for common values
$rgName='MyResourceGroup'
$location='eastus'

# Create a resource group.
New-AzResourceGroup -Name $rgName -Location $location

# Create virtual network 1.
$vnet1 = New-AzVirtualNetwork -ResourceGroupName $rgName -Name 'Vnet1' -AddressPrefix '10.0.0.0/16' -Location $location

# Create virtual network 2.
$vnet2 = New-AzVirtualNetwork -ResourceGroupName $rgName -Name 'Vnet2' -AddressPrefix '10.1.0.0/16' -Location $location

# Peer VNet1 to VNet2.
Add-AzVirtualNetworkPeering -Name 'LinkVnet1ToVnet2' -VirtualNetwork $vnet1 -RemoteVirtualNetworkId $vnet2.Id

# Peer VNet2 to VNet1.
Add-AzVirtualNetworkPeering -Name 'LinkVnet2ToVnet1' -VirtualNetwork $vnet2 -RemoteVirtualNetworkId $vnet1.Id

Clean up deployment

Run the following command to remove the resource group, VM, and all related resources:

Remove-AzResourceGroup -Name myResourceGroup -Force

Script explanation

This script uses the following commands to create a resource group, virtual machine, and all related resources. Each command in the following table links to command specific documentation:

Command Notes
New-AzResourceGroup Creates a resource group in which all resources are stored.
New-AzVirtualNetwork Creates an Azure virtual network and subnet.
Add-AzVirtualNetworkPeering Creates a peering between two virtual networks.
Remove-AzResourceGroup Deletes a resource group including all nested resources.

Next steps

For more information on the Azure PowerShell, see Azure PowerShell documentation.

More virtual network PowerShell script samples can be found in Virtual network PowerShell samples.