Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This script will rename all the VMs hosted by the current host based
- # on their Nova instance GUID (stored within VM notes).
- #
- # If the VM is clustered, the according cluster group/resources will be
- # renamed as well.
- function is_guid($string){
- $pattern = "^[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-" +
- "[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-" +
- "[0-9a-fA-F]{12}$"
- $string -match $pattern
- }
- write-host "Renaming Nova instances using their GUID."
- $cluster = get-cluster -ErrorAction SilentlyContinue
- if (!(cluster)){
- write-host "Could not retrieve any failover cluster. "`
- "Assuming the instances are not clustered."
- }
- else {
- write-host "Retrieved failover cluster. Any cluster VM resources "`
- "created by Nova will be renamed."
- }
- $vms = get-vm
- foreach($vm in $vms) {
- $vmName = $vm.Name
- $vmGUID = $vm.Notes
- # Nova stores the instance GUID within the instance notes field.
- if (!(is_guid $vmGUID)) {
- write-host "Skipping renaming instance '$vmName' as the "`
- "instance notes '$vmGUID' do not contain a GUID."`
- "Assuming it's not created by Nova."
- continue
- }
- # Check the VM name
- if ($vmName -eq $vmGUID) {
- write-host "Instance '$vmName' is already named using its GUID."
- }
- else {
- write-host "Renaming Nova instance '$vmName' to '$vmGUID'."
- set-vm $vm -NewVMName $vmGUID
- }
- # Rename the VM cluster group/resources, if found.
- if (!($cluster)) {
- continue
- }
- $group = get-clustergroup $vmName -ErrorAction SilentlyContinue
- if ($group) {
- write-host "Renaming cluster group '$vmName' to '$vmGUID'"
- $group.Name = $vmGUID
- }
- else {
- write-host "Could not find cluster group '$vmName'. "`
- "Assuming the instance is not clustered."
- continue
- }
- $vmClusResName = "Virtual Machine $vmName"
- $vmConfigClusResName = "Virtual Machine Configuration $vmName"
- $newVmClusResName = "Virtual Machine $vmGUID"
- $newVmConfigClusResName = "Virtual Machine Configuration $vmGUID"
- $vmClusRes = get-clusterresource $vmClusResName
- if ($vmClusRes) {
- write-host "Renaming cluster resource $vmClusResName to "`
- "$newVmClusResName"
- $vmClusRes.Name = $newVmClusResName
- }
- else {
- write-error "Could not find cluster resource $vmClusResName, "`
- "although the according cluster group was found."
- }
- $vmConfigClusRes = get-clusterresource $vmConfigClusResName
- if ($vmConfigClusRes) {
- write-host "Renaming cluster resource $vmClusResName to "`
- "$newVmClusResName"
- $vmConfigClusRes.Name = $newVmConfigClusResName
- }
- else {
- write-error "Could not find cluster resource $vmConfigClusRes, "`
- "although the according cluster group was found."
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement