Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Migrate ESXi VM to another datastore
#!/bin/sh
if [ $# -ne 3 ] ; then
echo "USAGE: ./$0 <vm name> <src datastore> <dest datastore>"
exit
fi
VM=$1
SRC=$2
DEST=$3
SRCDIR=/vmfs/volumes/$SRC/$VM
if [ ! -d $SRCDIR ] ; then
echo $SRCDIR does not exists.
exit
fi
VMID=`vim-cmd vmsvc/getallvms | grep $VM.vmx | awk -F' ' '{print $1}'`
if [ $VMID ] ; then
POWER=`vim-cmd vmsvc/power.getstate $VMID | grep Powered | awk -F' ' '{print $2}'`
if [ $POWER == 'on' ] ; then
# vim-cmd vmsvc/power.shutdown or poweroffという手もあるけど
# 考えるのが面倒になったので略
echo "VM $VM is powered on. Please turn off the power."
exit
fi
vim-cmd vmsvc/unregister $VMID
fi
DESTDIR=/vmfs/volumes/$DEST/$VM
if [ -d $DESTDIR ] ; then
echo $DESTDIR is exists.
exit
fi
mkdir $DESTDIR
cp $SRCDIR/$VM.vmx $DESTDIR/$VM.vmx
cp $SRCDIR/$VM.vmxf $DESTDIR/$VM.vmxf
cp $SRCDIR/$VM.nvram $DESTDIR/$VM.nvram
cp $SRCDIR/$VM.vmsd $DESTDIR/$VM.vmsd
cp $SRCDIR/vmware-*.log $DESTDIR/
cp $SRCDIR/$VM-*.hlog $DESTDIR/
VMDKS=`ls -1 $SRCDIR/*.vmdk | grep -v flat | awk -F'/' '{print $NF}'`
for VMDK in $VMDKS ; do
vmkfstools -i "$SRCDIR/$VMDK" "$DESTDIR/$VMDK" -d thin
done
if [ $VMID ] ; then
NEWVMID=`vim-cmd solo/registervm $DESTDIR/$VM.vmx`
vim-cmd vmsvc/power.on $NEWVMID &
sleep 5
MSGID=`vim-cmd vmsvc/message $NEWVMID | grep "Virtual machine message" | awk -F' ' '{print $NF}' | awk -F':' '{print $1}'`
vim-cmd vmsvc/message $NEWVMID $MSGID 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment