Posted On October 6, 2021

PowerShell: Rename Hyper-V Object and Clustered Role Resource

kimconnect 0 comments
blog.KimConnect.com >> Codes , Virtualization >> 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 *

Related Post

PowerShell: Purge, Destroy, or Empty a Directory!

# WARNING: THIS IS A VERY DESTRUCTIVE FUNCTION. IF EXECUTED AT THE WRONG DIRECTORY WHERE…

Bash Shell Quick If Then and Case Switch Statements

protocol=udp # or tcp # If-then implementation if [$protocol == udp] then prefix=@ else prefix=@@…

PowerShell: Office 365 Bulk Licensing, Changing IDs, Enabling POP3

Connect to Office 365 # Office 365 Global Admin Credential$username="O365globalAdmin"$password=ConvertTo-securestring "PASSWORDHERE" -AsPlainText -Force$cred = New-Object…