Skip to content

Instantly share code, notes, and snippets.

@jpluimers
Last active November 16, 2023 01:36
Show Gist options
  • Save jpluimers/44c54e680b5d2887e3a5 to your computer and use it in GitHub Desktop.
Save jpluimers/44c54e680b5d2887e3a5 to your computer and use it in GitHub Desktop.
vmware console command to suspend all VMs that are not yet suspended and waits until they all are suspended
#!/bin/sh
# https://wiert.me/2021/04/30/vmware-esxi-console-viewing-all-vms-suspending-and-waking-them-up-part-5/
RUNNING=0
vmids=`vim-cmd vmsvc/getallvms | sed -n -E -e "s/^([[:digit:]]+)\s+((\S.+\S)?)\s+(\[\S+\])\s+(.+\.vmx)\s+(\S+)\s+(vmx-[[:digit:]]+)\s*?((\S.+)?)$/\1/p"`
for vmid in ${vmids} ; do
# echo "Probing VM with id: $vmid."
powerState=`vim-cmd vmsvc/power.getstate ${vmid} | sed '1d'`
name=`vim-cmd vmsvc/get.config ${vmid} | sed -n -E -e '/\(vim.vm.ConfigInfo\) \{/,/files = \(vim.vm.FileInfo\) \{/ s/^ +name = "(.*)",.*?/\1/p'`
vmPathName=`vim-cmd vmsvc/get.config ${vmid} | sed -n -E -e '/files = \(vim.vm.FileInfo\) \{/,/tools = \(vim.vm.ToolsConfigInfo\) \{/ s/^ +vmPathName = "(.*)",.*?/\1/p'`
# echo "VM with id ${vmid} has power state ${powerState} (name = ${name}; vmPathName = ${vmPathName})."
if [ "${powerState}" == "Powered on" ] ; then
RUNNING=1
echo "Powered on VM with id ${vmid} and name: $name"
echo "Suspending VM with id ${vmid} and name: $name"
vim-cmd vmsvc/power.suspend ${vmid} > /dev/null &
fi
done
while true ; do
if [ $RUNNING -eq 0 ] ; then
echo "Gone..."
break
fi
RUNNING=0
for vmid in ${vmids} ; do
# echo "Probing VM with id: $vmid."
powerState=`vim-cmd vmsvc/power.getstate ${vmid} | sed '1d'`
name=`vim-cmd vmsvc/get.config ${vmid} | sed -n -E -e '/\(vim.vm.ConfigInfo\) \{/,/files = \(vim.vm.FileInfo\) \{/ s/^ +name = "(.*)",.*?/\1/p'`
vmPathName=`vim-cmd vmsvc/get.config ${vmid} | sed -n -E -e '/files = \(vim.vm.FileInfo\) \{/,/tools = \(vim.vm.ToolsConfigInfo\) \{/ s/^ +vmPathName = "(.*)",.*?/\1/p'`
# echo "VM with id ${vmid} has power state ${powerState} (name = ${name}; vmPathName = ${vmPathName})."
if [ "${powerState}" == "Powered on" ] ; then
RUNNING=1
echo "Waiting for id ${vmid} and name: $name..."
fi
done
sleep 1
done
exit 0
@AndersGoran
Copy link

Great, this works fine too!

@jpluimers
Copy link
Author

Great, this works fine too!

Glad it does. Always happy when things are also useful to others (:

@Nadahar
Copy link

Nadahar commented Mar 2, 2023

@jpluimers Thanks for making this. I couldn't get it to work however, and tracked it to that the initial sed on getallvms didn't match anything.

It turns out that I have spaces in all my volume names, which this doesn't expect. I replaced (\[\S+\]) with (\[[^]]+\]) and now it works fine also when there's spaces in the volume names.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment