Renaming Hyper-V VHD and VHDX with PowerShell - problems with syntax

I am trying to find a way to rename VHDs and VHDX's according to the Hyper-V VM name.  This script allows you to enter the name of the VM, and it will rename the disks to match the VM name.  

I'm having some issues with the syntax.  Eventually this needs to rename all VHDs and VHDX's if their names do not match.


#Enter Name for new VM
$VM = "VM1_Replica"
 
#Do not make any changes below this line
$vhd = Get-SCVirtualDiskDrive -VM $vm
Foreach ($vhd in $vhd)
{
    $oldName = $vhd.Path
    $newName = $oldName.Substring(0,$oldName.LastIndexOf("\")) `
                + "\" + $vhd.VMName + "_" + $vhd.ControllerType `
                + "_" + $vhd.ControllerNumber + "_" `
                + $vhd.ControllerLocation`
                + $oldName.Substring($oldName.LastIndexOf("."))
    Rename-Item $oldName $newName
    Set-SCVirtualDiskDrive -VMName $vhd.VMName -Path $newName `
        -ControllerType $vhd.ControllerType -ControllerNumber `
        $vhd.ControllerNumber -ControllerLocation `
        $vhd.ControllerLocation
}

Open in new window


I'm getting errors such as the ones below.  This may be related to VMM 2012 R2 PowerShell syntax being incorrect - this script may have been for an older version of VMM.

The environment this needs to work in is Server 2012 R2 and VMM 2012 R2.

You cannot call a method on a null-valued expression.
At line:11 char:5
+     $newName = $oldName.Substring(0,$oldName.LastIndexOf("\")) `
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
Rename-Item : Cannot bind argument to parameter 'Path' because it is null.
At line:16 char:17
+     Rename-Item $oldName $newName
+                 ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Rename-Item], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RenameItemCommand
 
Set-SCVirtualDiskDrive : A parameter cannot be found that matches parameter name 'VMName'.
At line:17 char:28
+     Set-SCVirtualDiskDrive -VMName $vhd.VMName -Path $newName `
+                            ~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-SCVirtualDiskDrive], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.SetVirtualDiskDriveCmdlet
JWeb AdminAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SubsunCommented:
I could see, you have assigned same name for both the variables in Foreach loop.. Try changing the name of collection variable.. For example..
$vhds = Get-SCVirtualDiskDrive -VM $vm
Foreach ($vhd in $vhds)

Open in new window

Ref : http://ss64.com/ps/foreach.html
0
JWeb AdminAuthor Commented:
Hmm.  I must have missed that.  Still looks like $vhd.Path is null.

You cannot call a method on a null-valued expression.
At line:9 char:5
+     $newName = $oldName.Substring(0,$oldName.LastIndexOf("\")) `
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
0
SubsunCommented:
I dont have access to my lab for testing.. So can you tell me, What you get for
Get-SCVirtualDiskDrive -VM "VM1_Replica" | select Path

Open in new window

0
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

JWeb AdminAuthor Commented:
Must be the syntax - if I do this:

Get-SCVirtualDiskDrive -VM "VM1_Replica" | select VirtualHardDisk

Open in new window


I get

VirtualHardDisk                                                                                                                                                      
---------------                                                                                                                                                      
VM1_Replica_disk_1                                                                                                                                            
VM2_Replica_disk_2
0
SubsunCommented:
Probably property name of the path might be different, use FL * to list all properties..
Get-SCVirtualDiskDrive -VM "VM1_Replica" | FL *

Open in new window

0
JWeb AdminAuthor Commented:
PS C:\Windows\system32> Get-SCVirtualDiskDrive -VM "testing123_Replica" | FL *



VirtualHardDiskId      : 72e5f248-483c-49c9-a0ef-2f8003b2a52b
VirtualHardDisk        : testing123_Replica_disk_1
PassThroughDisk        : 
IsVHD                  : True
HasSharedStorage       : False
CreateDiffDisk         : False
BusType                : IDE
Bus                    : 0
Lun                    : 0
PendingDiskAssociation : False
Classification         : Remote Storage
VolumeType             : BootAndSystem
ObjectType             : VirtualDiskDrive
Accessibility          : Public
Name                   : testing123_Replica
IsViewOnly             : False
Description            : 
AddedTime              : 8/21/2014 4:10:43 PM
ModifiedTime           : 8/21/2014 6:40:40 PM
Enabled                : True
MostRecentTask         : 
ServerConnection       : Microsoft.SystemCenter.VirtualMachineManager.Remoting.ServerConnection
ID                     : a49d482f-9350-4670-ac14-18379f2a0131
MarkedForDeletion      : False
IsFullyCached          : True
MostRecentTaskIfLocal  : 

VirtualHardDiskId      : 2a9729da-280c-4305-87c9-d9709bb0afc6
VirtualHardDisk        : testing123_Replica_disk_2
PassThroughDisk        : 
IsVHD                  : True
HasSharedStorage       : False
CreateDiffDisk         : False
BusType                : IDE
Bus                    : 0
Lun                    : 1
PendingDiskAssociation : False
Classification         : Remote Storage
VolumeType             : None
ObjectType             : VirtualDiskDrive
Accessibility          : Public
Name                   : testing123_Replica
IsViewOnly             : False
Description            : 
AddedTime              : 8/21/2014 5:06:27 PM
ModifiedTime           : 8/21/2014 6:40:40 PM
Enabled                : True
MostRecentTask         : 
ServerConnection       : Microsoft.SystemCenter.VirtualMachineManager.Remoting.ServerConnection
ID                     : 3dc21fdd-0ea1-4591-9b13-41d93c9a4cc6
MarkedForDeletion      : False
IsFullyCached          : True
MostRecentTaskIfLocal  : 

Open in new window

0
JWeb AdminAuthor Commented:
Strange, I don't see the path anywhere.  It should look something like this:

\\sofs01\VMstorage1\testing123_Replica\files_in_here.vhd
0
SubsunCommented:
Try..
Get-VMHardDiskDrive -VM "VM1_Replica" | select Path

Open in new window

0
JWeb AdminAuthor Commented:
This works:

PS C:\Windows\system32> Get-VM | select Location


Location                                                                                                                                                              
--------                                                                                                                                                              
\\sofs01.domain.com\VMstorage1\testing123_Replica                                                                                                                 
\\sofs01\VMstorage1\testing123_Replica.domain.com                                                                                                                            
C:\ProgramData\Microsoft\Windows\Hyper-V 

Open in new window

0
SubsunCommented:
I will test it in may lab as soon as I get a chance..
0
JWeb AdminAuthor Commented:
OK.  If you happen to know of a better alternative to rename the virtual disks through VMM, I'm all ears.  So far, I have not been able to find a Powershell cmdlet that has the ability to rename a VHD - only create new, or remove.
0
SubsunCommented:
Sorry for the long delay.. I have tried Get-VMHardDiskDrive command in my lab and I am able to get the path details. What you get the result for following command?
Get-VMHardDiskDrive -VM "VM1_Replica" | select Path
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JWeb AdminAuthor Commented:
Hello - we've solved this by configuring different job options in our migration process.  I'll give you the points since you were kind enough to help!
0
SubsunCommented:
Thanks & I am glad that you were able to resolve your issue. For the readers, I am able to test this successfully using commands Get-VMHardDiskDriveSet-VMHardDiskDrive instead of Get-SCVirtualDiskDriveSet-SCVirtualDiskDrive
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.