720-chg-disk-type
#!/bin/bash
#
# Script to change VM's disk type
#
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 "
 
Review harddisk parameters ...
"
VBoxManage showhdinfo $VB_VM_DISK
echo "
Validate Disk types are,
  normal|writethrough|immutable|
  shareable|readonly|multiattach"
echo -n "Enter disk type :"
read VB_VM_HD_TYPE
#
# To change disk type you have to detach, change and reattach
VBoxManage storageattach ${VB_VM_NAME} \
 --storagectl "${VB_VM_SATA}" \
 --port $VB_VM_PORT --device $VB_VM_DEVICE \
 --type hdd --medium none
VBoxManage modifyhd $VB_VM_DISK --type $VB_VM_HD_TYPE
VBoxManage storageattach ${VB_VM_NAME} \
 --storagectl "${VB_VM_SATA}" \
 --port $VB_VM_PORT --device $VB_VM_DEVICE \
 --type hdd --medium $VB_VM_DISK
#
VBoxManage showhdinfo $VB_VM_DISK
echo "Done!"
exit