更新ARM虚拟机网卡名称使其符合命名规则
通过Azure Portal创建过虚拟机的同学都会注意到一个问题:其他资源命名都可以自定义,唯独网络接口的命名会默认带3位随机数,若企业对命名规则有要求的情况下,这显然是不可以的。通过下面的PowerShell脚本我们可以对每个虚拟机进行网络接口替换,以达到目的。
单网卡已测试通过。
使用下面PowerShell脚本可以将默认网络接口替换成名称为“虚拟机名-nic”的:
#------------------------------------------------------------------------------
# User own the risk, otherwise exit.
#
# Azure PowerShell Version: 3.6.0
#
# Create by Zeno.
#------------------------------------------------------------------------------
"------------------------------------------------------------------------------ " | Write-Host -ForegroundColor Yellow
"" | Write-Host -ForegroundColor Yellow
"`t脚本说明: " | Write-Host -ForegroundColor Yellow
"" | Write-Host -ForegroundColor Yellow
"`t1.本脚本默认公共IP、网络接口、虚拟机均在同一个资源组内 " | Write-Host -ForegroundColor Yellow
"`t2.本脚本默认名称规则为 公共IP:虚拟机名-ip 网络接口:虚拟机名-nic " | Write-Host -ForegroundColor Yellow
"`t3.如果公共IP名称相同,请在脚本运行时选择覆盖创建" | Write-Host -ForegroundColor Yellow
"`t4.本脚本会改变虚拟机公共IP地址/私有IP地址,请谨慎使用" | Write-Host -ForegroundColor Yellow
"------------------------------------------------------------------------------ " | Write-Host -ForegroundColor Yellow
#登录订阅
#Login-AzureRmAccount -EnvironmentName AzureChinaCloud -Credential $(Get-Credential -UserName admin@xxx.partner.onmschina.cn -Message Login_AzureChinaCloud) |Out-Null
#定义参数
$vm = Get-AzureRmVM | Select-Object Name,ResourceGroupName,NetworkInterfaceIDs,Location | Out-GridView -PassThru -Title "Select your VM"
#$VNet = Get-AzureRmVirtualNetwork | Select Name,ResourceGroupName | Out-GridView -PassThru -Title "Select your VNet"
$Subnet = Get-AzureRmVirtualNetwork | Get-AzureRmVirtualNetworkSubnetConfig | Select-Object Name,Id,AddressPrefix| Out-GridView -PassThru -Title "Select your Subnet"
$vmName = $vm.Name
$NewNIC = ("$vmName" + "-nic").ToLower()
$NewpublicIp = "$vmName" + "-ip"
#获取虚拟机对象
$myvm = Get-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name
#取消网络接口关联
$nic = Get-AzureRmNetworkInterface -ResourceGroupName $vm.ResourceGroupName -Name $myvm.NetworkProfile.NetworkInterfaces.Id.Split("/")[-1]
$nic.IpConfigurations.PublicIpAddress.Id = $null
Set-AzureRmNetworkInterface -NetworkInterface $nic | Out-Null
#创建公共IP
write-host "`n`tCreate Public Ip: $NewpublicIp!" -ForegroundColor Green
$myPublicIp = New-AzureRmPublicIpAddress -Name $NewpublicIp -ResourceGroupName $vm.ResourceGroupName -Location $vm.Location -AllocationMethod Dynamic
#创建新的网络接口
write-host "`n`tCreate Newwork Interface: $NewNIC!" -ForegroundColor Green
$myNIC = New-AzureRmNetworkInterface -Name $NewNIC -ResourceGroupName $vm.ResourceGroupName -Location $vm.Location -SubnetId $Subnet.Id -PublicIpAddressId $myPublicIp.Id
#删除默认网络接口
$removenic = Remove-AzureRmVMNetworkInterface -VM $myvm -NetworkInterfaceIDs $vm.NetworkInterfaceIDs[0]
#添加新的网络接口
write-host "`n`tReplace Newwork Interface to: $NewNIC!" -ForegroundColor Green
Add-AzureRmVMNetworkInterface -VM $myvm -Id $myNIC.Id –Primary | Update-AzureRmVM