PowerShell: Rename Hyper-V Object and Clustered Role Resource

$oldName='testWindows'
$newName='server01.intranet.kimconnect.com'

# Rename Hyper-V Clustered Resource: Guess VM
$vm=Get-clustergroup -Cluster (get-cluster).Name -Name $oldName
$vm.Name=$newName

# Rename Hyper-V Object. This must be executed on the owner node
$ownerNode=$vm.OwnerNode
invoke-command -computername $ownerNode {
    param ($oldName,$newName)
    try{
        Rename-VM $oldName -NewName $newName
        write-host "Guest VM $oldName has been renamed to $newName"
        stop-vm $newName
        $disks=(get-vm $newName|Get-VMHardDiskDrive).Path
        $primaryStoragePath=$disks|%{split-path $_ -parent}|select -first 1
        $newPath=$(split-path $primaryStoragePath -Parent)+'\'+$newName
        $null=mkdir $newPath -force    
        Move-VMStorage $newName -DestinationStoragePath $newPath
        start-vm $newName
        write-host "Old storage path: $primaryStoragePath`r`nNew Storage Path: $newPath"
        write-host "Please verify that the old storage path is empty and remove old storage path manually."
    }catch{
        write-warning $_
    }
} -Args $oldName,$newName
Sample Output:

Guest VM testWindows has been renamed to server01.intranet.kimconnect.com
Old storage path: \\fileserver\vms\testWindows
New Storage Path: \fileserver\vms\server01.intranet.kimconnect.com
Please verify that the old storage path is empty and remove old storage path manually.

Leave a Reply

Your email address will not be published. Required fields are marked *