Solved

Move more than VM to another host with same command

Posted on 2010-08-21
23
1,601 Views
Last Modified: 2013-11-06
I found this script from here http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/30/hey-scripting-guy-march-30-2010.aspx


It's working as it should. But I would like to move multiple VM in same time. So can some one assist me how I can modify that script that I could move more than VM to another host?

# Connect to the VMM server.

Get-VMMServer –ComputerName “VMMServer01.Contoso.com”

# Get the host that you want to move the virtual machine to.

$VMHost = Get-VMHost –ComputerName “VMHost01.Contoso.com”

#Get the virtual machine.

$VM = Get-VM -Name "VM01"

# Specify the path on the host.

$VMPath = $VMHost.VMPaths[0]

# Migrate the virtual machine.

Move-VM -VM $VM -VMHost $VMHost -Path $VMPath
0
Comment
Question by:thaapavuori
  • 10
  • 10
  • 3
23 Comments
 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility
Hey,

I can't test this kind of thing, but can you use something like this?


Get-VM -Server "VMHost01.Contoso.com" | ForEach-Object {
  Move-VM -VM $_ -VMHost "VMHost01.Contoso.com" -Path $_.VMPaths[0]
}


Chris
0
 

Author Comment

by:thaapavuori
Comment Utility
Thanks. As much as I understand this script will move all VMs from one host? I would like to move hosts with spesific names (e.g. VM1, VM3 and VM10) or all VMs which start as VM100 (if I have like example VM1001, VM1002...).

Thanks again :)
0
 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility

Get-VM appears to support Wildcards, so you should be able to do:


Get-VM -Name "VM100*" -Server "VMHost01.Contoso.com" | ForEach-Object {
  Move-VM -VM $_ -VMHost "VMHost01.Contoso.com" -Path $_.VMPaths[0]
}


If not, we can filter that part using Where-Object.

Chris
0
 

Author Comment

by:thaapavuori
Comment Utility
Hi,

Thanks, I tried that. It didnt work. First it didnt like that parameter "-Server".

Here it that error which I got.
Get-VM : A parameter cannot be found that matches parameter name 'Server'.
At line:1 char:30
+ Get-VM -Name "test*" -Server <<<<  "vmhost.domain.local" | ForEach-Objec
t {  Move-VM -VM $_ -VMHost "vmhost.domain.local" -Path $_.VMPaths[0]}
    + CategoryInfo          : InvalidArgument: (:) [Get-VM], ParameterBindingE
   xception
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.SystemCenter.Vi
   rtualMachineManager.Cmdlets.GetVMCmdlet
0
 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility
Ah, sorry, my fault.

I was looking at the help for the VSphere (VMWare) CmdLets, my syntax is bad.

Can you run this and see if it offers a server name parameter at all?

Get-Help Get-VM

Chris
0
 

Author Comment

by:thaapavuori
Comment Utility
Here it comes:

NAME
    Get-VM
   
SYNOPSIS
    Gets virtual machine objects from the Virtual Machine Manager database.
   
   
SYNTAX
    Get-VM [[-Name] <String>] -VMHost [<String Host>] [-VMMServer [<String Serv
    erConnection VMMServer>]] [<CommonParameters>]
   
    Get-VM [[-Name] <String>] [-VMMServer [<String ServerConnection VMMServer>]
    ] [<CommonParameters>]
   
    Get-VM [[-Name] <String>] [-ID [<Guid String>]] [-VMMServer [<String Server
    Connection VMMServer>]] [<CommonParameters>]
   
    Get-VM [[-Name] <String>] [-All] [-VMMServer [<String ServerConnection VMMS
    erver>]] [<CommonParameters>]
   
   
DESCRIPTION
    Gets one or more objects that represent virtual machines from the Virtual M
    achine Manager database. A virtual machine can be deployed on a virtual mac
    hine host or can be stored in the Virtual Machine Manager library.
   

RELATED LINKS
    Get-VMMServer
    Move-VM
    New-VM
    Refresh-VM
    Remove-VM
    Repair-VM
    Resume-VM
    SaveState-VM
    Set-VM
    Shutdown-VM
    Start-VM
    Stop-VM
    Store-VM
    Suspend-VM

REMARKS
    To see the examples, type: "get-help Get-VM -examples".
    For more information, type: "get-help Get-VM -detailed".
    For technical information, type: "get-help Get-VM -full".

0
 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility

Cool, thanks. Lets see if this plays:

Get-VM -Name "VM100*" -VMMServer "VMHost01.Contoso.com" | ForEach-Object {
  Move-VM -VM $_ -VMHost "VMHost01.Contoso.com" -Path $_.VMPaths[0]
}

You may have to check all of the commands in my example, I don't have the MS VM tools around.

Regarding the Name parameter, it'd be nice to confirm whether or not it supports wildcards by running:

Get-Help Get-VM -Parameter Name

We're looking for "accept wildcard characters?", and we want it to be True :)

Chris
0
 

Author Comment

by:thaapavuori
Comment Utility
Here is the output of Get-Help Get-VM -Parameter Name

So it doesnt support wildcard :(

PS C:\Windows\system32> Get-Help Get-VM -Parameter Name

-Name <String>
    Specifies the name of a VMM object.

    Required?                    false
    Position?                    0
    Default value
    Accept pipeline input?       false
    Accept wildcard characters?  false
0
 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility

Okay, no problem. Lets do Where-Object :)


Get-VM -VMMServer "VMHost01.Contoso.com" | Where-Object { $_.Name -Like "VM100*" } | ForEach-Object {
  Move-VM -VM $_ -VMHost "VMHost01.Contoso.com" -Path $_.VMPaths[0]
}


Chris
0
 

Author Comment

by:thaapavuori
Comment Utility
There is still something.

Cannot index into a null array.
At line:1 char:170
+ Get-VM -VMMServer "vmm.domain.local" | Where-Object { $_.Name -Like "test
i*" } | ForEach-Object {  Move-VM -VM $_ -VMHost "host.domain.local" -Pat
h $_.VMPaths[ <<<< 0]}
    + CategoryInfo          : InvalidOperation: (0:Int32) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Cannot index into a null array.
At line:1 char:170
+ Get-VM -VMMServer "vmm.domain.local" | Where-Object { $_.Name -Like "test
i*" } | ForEach-Object {  Move-VM -VM $_ -VMHost "host.domain.local" -Pat
h $_.VMPaths[ <<<< 0]}
    + CategoryInfo          : InvalidOperation: (0:Int32) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Cannot index into a null array.
At line:1 char:170
+ Get-VM -VMMServer "vmm.domain.local" | Where-Object { $_.Name -Like "test
i*" } | ForEach-Object {  Move-VM -VM $_ -VMHost "host.domain.local" -Pat
h $_.VMPaths[ <<<< 0]}
    + CategoryInfo          : InvalidOperation: (0:Int32) [], RuntimeException
    + FullyQualifiedErrorId : NullArray


This Char is about this VMPath.

Timo
0
 

Author Comment

by:thaapavuori
Comment Utility
Sorry, I meant At line:1 char:170 is about VMPath :)
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility

Hmm lets try this, see if we can filter those out.


Get-VM -VMMServer "VMHost01.Contoso.com" | Where-Object { $_.Name -Like "VM100*" -And $_.VMPaths } | ForEach-Object {
  Move-VM -VM $_ -VMHost "VMHost01.Contoso.com" -Path $_.VMPaths[0]
}


But you might check that Get-VM is returning VMPaths for something here, otherwise we'll filter everything out with this.

Chris
0
 

Author Comment

by:thaapavuori
Comment Utility
Now I didnt get any error message when I excuted the command but nothing happen neather. Here is the output of Get-VM.



VMCPath                           : d:\hyper-v\Testi1\Virtual Machines\94F39A47
                                    -737D-4B27-AE32-5AE868328871.xml
MarkedAsTemplate                  : False
VMId                              : 94F39A47-737D-4B27-AE32-5AE868328871
VMResourceGroup                   :
VMConfigResource                  :
VMResource                        :
UnsupportedReason                 : Success (0)
HostGroupPath                     : All Hosts\Testi1
TotalSize                         : 0
HasPassthroughDisk                : False
Status                            : PowerOff
StatusString                      : Stopped
StartAction                       : NeverAutoTurnOnVM
StopAction                        : SaveVM
RunGuestAccount                   :
DelayStart                        : 0
CPUUtilization                    : 0
PerfCPUUtilization                : 0
PerfDiskBytesRead                 : 0
PerfDiskBytesWrite                : 0
PerfNetworkBytesRead              : 0
PerfNetworkBytesWrite             : 0
VirtualizationPlatform            : HyperV
ComputerNameString                : Unknown
CreationSource                    : Unknown source object
IsUndergoingLiveMigration         : False
SourceObjectType                  : Unknown source object
OperatingSystemShutdownEnabled    : True
TimeSynchronizationEnabled        : True
DataExchangeEnabled               : True
HeartbeatEnabled                  : True
BackupEnabled                     : True
ExcludeFromPRO                    : False
FailedJobID                       :
CheckpointLocation                : d:\hyper-v\Testi1
SelfServiceUserRole               :
PassThroughDisks                  : {}
LastRestoredVMCheckpoint          :
Location                          : d:\hyper-v\Testi1
CreationTime                      : 23.8.2010 14:18:41
OperatingSystem                   : Windows Server 2003 Enterprise x64 Edition
HasVMAdditions                    : False
VMAddition                        : Not Detected
NumLockEnabled                    : False
CPUCount                          : 1
IsHighlyAvailable                 : False
LimitCPUFunctionality             : False
LimitCPUForMigration              : False
Memory                            : 512
BootOrder                         : {CD, IdeHardDrive, PxeBoot, Floppy}
ComputerName                      :
UseHardwareAssistedVirtualization : True
SANStatus                         : {DeployVMNonSANDisk (1209)}
CostCenter                        :
QuotaPoint                        : 1
UserRoleID                        : 00000000-0000-0000-0000-000000000000
IsTagEmpty                        : False
Tag                               : (none)
CustomProperties                  : {, , , ...}
UndoDisksEnabled                  : False
CPUType                           : 1.20 GHz Athlon MP
ExpectedCPUUtilization            : 20
DiskIO                            : 0
NetworkUtilization                : 0
RelativeWeight                    : 100
CPUReserve                        : 0
CPUMax                            : 100
VirtualDVDDrives                  : {Testi1}
VirtualHardDisks                  : {}
VirtualDiskDrives                 : {}
ShareSCSIBus                      : False
VirtualNetworkAdapters            : {Testi1}
VirtualFloppyDrive                : Testi1
VirtualCOMPorts                   : {COM1, COM2}
VirtualSCSIAdapters               : {}
VMCheckpoints                     : {}
TieredPerfData                    : 56c7d096-9b36-4f7d-aae9-bcc4a5379515
HostId                            : d172ccb8-d9ac-491f-aa4d-7c2f45eaeb05
HostType                          : VMHost
HostName                          : host1.domain.local
VMHost                            : host1.domain.local
LibraryServer                     :
LibraryGroup                      :
Owner                             : domain\username
OwnerSid                          : S-1-5-21-329068152-1229272821-725345543-361
                                    8
ObjectType                        : VM
Accessibility                     : Public
Name                              : Testi1
Description                       :
AddedTime                         : 23.8.2010 14:18:41
ModifiedTime                      : 23.8.2010 14:25:12
Enabled                           : True
MostRecentTask                    :
ServerConnection                  : Microsoft.SystemCenter.VirtualMachineManage
                                    r.Remoting.ServerConnection
ID                                : 56c7d0c3-9b36-4f7d-aae9-bcc4a5379515
MarkedForDeletion                 : False
IsFullyCached                     : True



Thanks again :)
0
 
LVL 15

Expert Comment

by:msmamji
Comment Utility
If nothing is happening then most probably your target and source host/node are the same
0
 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility

Ah sorry, should have read the original a bit more careful.

Lets see...

So, we're going from $VMServer and we're moving to $VMHost using the first path on $VMHost. If so... this "should" be a little more accurate.

Chris
$VMHost = "VMHost01.Contoso.com"
$Path = (Get-VMHost $NewHost).VMPaths[0]

$VMServer = "VMMServer01.Contoso.com"
Get-VM -VMMServer $VMServer | Where-Object { $_.Name -Like "VM100*" } | ForEach-Object {
  Move-VM -VM $_ -VMHost $VMHost -Path $Path
}

Open in new window

0
 

Author Comment

by:thaapavuori
Comment Utility
Sorry but still something.

This $Path has something which doesnt work.

PS C:\Windows\system32> $Path = (Get-VMHost $NewHost).VMPaths[0]
Get-VMHost : Cannot validate argument on parameter 'ComputerName'. The argument
 is null, empty, or an element of the argument collection contains a null value
. Supply a collection that does not contain any null values and then try the co
mmand again.
At line:1 char:20
+ $Path = (Get-VMHost <<<<  $NewHost).VMPaths[0]
    + CategoryInfo          : InvalidData: (:) [Get-VMHost], ParameterBindingV
   alidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Syste
   mCenter.VirtualMachineManager.Cmdlets.GetHostCmdlet

Thanks about your time and effort.
0
 
LVL 70

Accepted Solution

by:
Chris Dent earned 500 total points
Comment Utility

That'd be me making partial changes to variable names again.

Chris
$VMHost = "VMHost01.Contoso.com"
$Path = (Get-VMHost $VMHost).VMPaths[0]

$VMServer = "VMMServer01.Contoso.com"
Get-VM -VMMServer $VMServer | Where-Object { $_.Name -Like "VM100*" } | ForEach-Object {
  Move-VM -VM $_ -VMHost $VMHost -Path $Path
}

Open in new window

0
 
LVL 15

Expert Comment

by:msmamji
Comment Utility
I think you are getting this error because $NewHost is not initialized, meaning it has no value defined. You should define it like
$NewHost = "VMhost2.contoso.com"
or whatever it the name of the host you are moving the VMs to.
0
 
LVL 15

Expert Comment

by:msmamji
Comment Utility
disregard my last comment.
0
 

Author Comment

by:thaapavuori
Comment Utility
Thanks. Now it was working as it should. Before you can run these command you need to connect to vmm server by powershell (Get-VMMServer –ComputerName “vmm.domain.local”).

If you still have time. How I should modify the script if I want to move some spesific VMs to other host. Like WindowsXP, WindowsServer2003 and Windows7. I mean that I dont want to move Windows* to other host just spesified names of VMs.

Thanks. This script which you already did for me will help me a lot when Im working with my virtual environment.

Timo
0
 
LVL 70

Assisted Solution

by:Chris Dent
Chris Dent earned 500 total points
Comment Utility
If you have a small number of definite names you can do this (in theory at least).

Is that what you mean?

Chris


$VMs = "WindowsXP", "WindowsServer2003", "Windows7"

$VMHost = "VMHost01.Contoso.com"
$Path = (Get-VMHost $VMHost).VMPaths[0]

$VMServer = "VMMServer01.Contoso.com"
$VMs | ForEach-Object {
  Get-VM -Name $_ -VMMServer $VMServer | Move-VM -VMHost $VMHost -Path $Path
}

Open in new window

0
 

Author Comment

by:thaapavuori
Comment Utility
Thank you very much. This your script worked just as I hoped. I really appreciate the time that spent for me :)
0
 
LVL 70

Expert Comment

by:Chris Dent
Comment Utility

You're most welcome :)

Chris
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Are you one of those front-line IT Service Desk staff fielding calls, replying to emails, all-the-while working to resolve end-user technological nightmares? I am! That's why I have put together this brief overview of tools and techniques I use in o…
In this previous article (https://oddytee.wordpress.com/2016/05/05/provision-new-office-365-user-and-mailbox-from-exchange-hybrid-via-powershell/), we made basic license assignments to users in O365. When I say basic, the method is the simplest way …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now