Issue
Shell Script: How i can list trough cli of virtualbox the vms and delete all but one called "SaveThisOne"?
CAUTION: The lines below deletes all virtualbox vms:
class="lang-bash prettyprint-override">VBoxManage list runningvms | awk '{print $2;}' | xargs -I vmid VBoxManage controlvm vmid poweroff
VBoxManage list vms | awk '{print $2;}' | xargs -I vmid VBoxManage unregistervm --delete vmid
Possible solution, after the help of the guys here, pmf, BeatOne and tripleee what i did was:
#!/bin/bash
#This script list all VM's through virtualbox cli, vboxmanage, do poweroff and deletes the virtual machines case they don't are listed in $vmnames variable.
# list all VM's
vboxmanage list vms |
awk -F '"' '{print $2}' |
while read -r vmnames; do
case $vmnames in
"Win10" | "Ubuntu" | "YourVMNameToSave" ) continue;;
esac
# poweroff and delete case name is not listed in $vmnames variable as a string.
vboxmanage controlvm "$vmnames" poweroff
vboxmanage unregistervm "$vmnames" --delete
done
Solution
i think the output of vmboxmanage list vms
looks like this:
"SaveThisOne" {asdgfdasg}
"DeleteThis" {asdfasdfasdg}
"AndThis" {gasdfas}
"AndThisToo" {asdfas}
Here is an Example:
#!/bin/bash
# list all VMs
vms=$(vboxmanage list vms)
# Check every vm
while read -r line; do
# Get VM name
vm_name=$(echo "$line" | awk -F'"' '{print $2}')
echo $vm_name
# check name and delete
if [ "$vm_name" != "SaveThisOne" ]; then
# delete if name not like
vboxmanage unregistervm "$vm_name" --delete
fi
done <<< "$vms"
i think that should do the job, but i have not tested it, so be careful
Answered By - BeatONE Answer Checked By - Robin (WPSolving Admin)