Having trouble with a script to move Hyper-V VM's

973 views Asked by At

I am trying to write a script that will take the hyper-V host as an input as well as the search string for the list of VM's I want to move...this is all via SCCM VMM, and its all 2012R2

Here is what I have so far...

$VMHOST = read-host "Enter the HyperV host you want to move your VM's to"

$SEARCHPATTERN = read-host "Enter the search pattern for the VM's you want to move"

$VMLIST = Get-SCVirtualMachine | Where-Object {$_.Name -like "*$SEARCHPATTERN*"} |format-table name -HideTableHeaders

foreach ($VMM in $VMLIST)
{

Move-SCVirtualMachine -VM $VMM -VMHost $VMHOST

}

If I run it, I get...

Move-SCVirtualMachine : Cannot bind parameter 'VM'. Cannot convert the "Microsoft.PowerShell.Commands.Internal.Format.FormatEndData" value of type "Microsoft.PowerShell.Commands.Internal.Format.FormatEndData" to type "Microsoft.SystemCenter.VirtualMachineManager.VM". At C:\Users\jfalcon\Desktop\vmmove.ps1:6 char:27 + Move-SCVirtualMachine -VM $VMM -VMHost $VMHOST + ~~~~ + CategoryInfo : InvalidArgument: (:) [Move-SCVirtualMachine], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.DeployVMCmdlet

Any ideas? Is the $VMLIST output not formatted correctly?

1

There are 1 answers

4
Matt On BEST ANSWER

Never use format-anything if you intend to continue processing the data. People use it for "nice" output to text file ( if you like console tables ) but it is for appearances only. PowerShell has converted your object into [Microsoft.PowerShell.Commands.Internal.Format.FormatEndData] for the purpose of displaying on screen. At that point the original object is destroyed.

You need to extract the right property from your Get-SCVirtualMachine using Select-Object -Expandproperty of just using dot notation if you PowerShell Version at least 3.0.

$VMLIST = Get-SCVirtualMachine | 
    Where-Object {$_.Name -like "*$SEARCHPATTERN*"} | 
    Select-Object -ExpandProperty Name

That should do the trick.