如何使用VirtualBox CLI重新启动VM并等待其完全启动?

问题描述

我正在使用VBoxManage unattended install自动创建VM,并希望在安装后运行脚本,这导致我选择了--post-install-command。 这里的问题是:脚本中的下一步需要“来宾添加”,因此我在安装中使用了--install-additions选项。不幸的是,此选项在安装Guest Additions之后不会重新启动计算机,因此,我正在寻找一种解决方法,以便从主机或来宾重新启动VM,然后继续执行主脚本。

解决方法

不幸的是,我在虚拟机启动时没有发现 VBox 触发的任何事件,所以我不得不等待它完全启动。

完全启动平均需要 2-3 分钟,所以我使用了 3 分钟的计时器。

$postInstallCommands = 'VBoxControl guestproperty set installation_finished y && (shutdown /s || shutdown -P now)'

########## Initiate unattended installation
VBoxManage unattended install "$vmName"  `
    --iso="$isoFile"                         `
    --user="$userName"                       `
    --password="$password"                   `
    --full-user-name="$userName"             `
    --install-additions                      `
    --locale=en_US                           `
    --country=US                             `
    --time-zone=EST                          `
    --image-index=1                          `
    --post-install-command="$postInstallCommands" *> $null
    
########## Start VM and wait to finish install
VBoxManage startvm "$vmName" --type headless

Write-Host "Waiting for VM to finish OS installation..."
VBoxManage guestproperty wait "$vmName" installation_finished *> $null

Start-Sleep -s 180