725-chg-disk-loc
#!/bin/bash
#
# Script to change VM's disk file location
#
if [ "$UID" -eq 0 ]
  then echo "This script should NOT be run as root."
  exit 1
fi
#
# Source config file
if [ ! -f ~/.vbconfig ]; then
    echo "Config File ~/.vbconfig not found!"
    echo "Run: set-folders to create .vbconfig"
    exit 1
fi
. ~/.vbconfig
#
if [ $# -ne 1 ]; then
  echo "Usage for $0 : VM Name required as argument."
  exit 1
fi
#
# Virtual Machine Name
VB_VM_NAME=$1
#
# Determine Name of SATA Controller
# This script not tested with multiple controllers!
VB_VM_SATA=`VBoxManage showvminfo ${VB_VM_NAME}| \
grep "Storage Controller Name"|cut -d":" -f2|sed 's/^[ ]*//'`
#
VB_VM_NO_SNAP_MSG="This machine does not have any snapshots"
VB_VM_NO_SNAP=`VBoxManage snapshot "${VB_VM_NAME}" list|grep -c "$VB_VM_NO_SNAP_MSG"`
if [ $VB_VM_NO_SNAP -eq 0 ]; then
  echo "VM $VB_VM_NAME has snapshots. Cannot proceed with snapshots."
  echo "Exiting ..."
  exit 1
fi
#
VM_POWERED_OFF=`VBoxManage showvminfo ${VB_VM_NAME}|\
 grep State|grep -c "powered off"`
if [ $VM_POWERED_OFF -eq 0 ]; then
  echo "VM $VB_VM_NAME is up or saved. Please power-down VM to continue"
  echo "Exiting ..."
  exit 1
fi
#
echo "
List of attached disks below ...
"
VBoxManage showvminfo ${VB_VM_NAME}|grep "${VB_VM_SATA}"
echo "
Choose the details of the disk whose type to change"
echo "Enter Port, Device and Disk Path
"
echo -n "Enter the port  :"
read VB_VM_PORT
echo -n "Enter the device:"
read VB_VM_DEVICE
echo -n "Enter disk path :"
read VB_VM_DISK
echo -n "Enter disk new path :"
read VB_VM_NEW_DISK
#
echo "
 
Review harddisk parameters ...
"
VBoxManage showhdinfo $VB_VM_DISK
echo
echo "Hard disk file will be relocated now ..."
read -p "Press [Enter] key to continue or [Ctrl-C] to break ..."
#
# To relocate disk file you have to detach, move file and reattach
VBoxManage storageattach ${VB_VM_NAME} \
 --storagectl "${VB_VM_SATA}" \
 --port $VB_VM_PORT --device $VB_VM_DEVICE \
 --type hdd --medium none
VBoxManage closemedium disk $VB_VM_DISK
mv $VB_VM_DISK $VB_VM_NEW_DISK
VBoxManage storageattach ${VB_VM_NAME} \
 --storagectl "${VB_VM_SATA}" \
 --port $VB_VM_PORT --device $VB_VM_DEVICE \
 --type hdd --medium $VB_VM_NEW_DISK
#
echo "Done!"
exit