-
Notifications
You must be signed in to change notification settings - Fork 0
/
rename.ps1
34 lines (24 loc) · 1.13 KB
/
rename.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#Variables
$resourceGroupName = "example-resources"
$vmName = "old-vm-name"
$newVmName = "new-vm-name"
$location = "West Europe"
# Get the VM
$vm = Get-AzVM -ResourceGroupName $resourceGroupName -Name $vmName
# Stop the VM
Stop-AzVM -ResourceGroupName $resourceGroupName -Name $vmName -Force
# Deallocate the VM
Stop-AzVM -ResourceGroupName $resourceGroupName -Name $vmName -StayProvisioned -Force
# Get the VM configuration
$vmConfig = New-AzVMConfig -VMSize $vm.HardwareProfile.VmSize -VMName $newVmName
# Set the OS disk
Set-AzVMOSDisk -VM $vmConfig -ManagedDiskId $vm.StorageProfile.OsDisk.ManagedDisk.Id -CreateOption Attach -Windows
# Set the network interface
$nic = Get-AzNetworkInterface -ResourceGroupName $resourceGroupName -Name $vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/')[-1]
Add-AzVMNetworkInterface -VM $vmConfig -Id $nic.Id
# Remove the old VM
Remove-AzVM -ResourceGroupName $resourceGroupName -Name $vmName -Force
# Create the new VM with the same resources
New-AzVM -ResourceGroupName $resourceGroupName -Location $location -VM $vmConfig
# Start the new VM
Start-AzVM -ResourceGroupName $resourceGroupName -Name $newVmName