Table of Contents
Missing While or Until Keyword in Do Loop PowerShell
We’re writing a PowerShell script to create a VirtualBox virtual machine. We want to print a menu to select Windows edition to install.
$menu = {
Write-Host "
Select an option:
1. Windows 10
2. Windows 11
"
Write-Host "Select an option and press Enter: " -nonewline
}
cls
$vmCreation = {VBoxManage createvm --name $vmName --ostype $ostype --register}
Do {
cls
Invoke-Command $menu
$select = Read-Host
if ($select -eq 1) {$osName = 'Windows'; $osNumber ='10'; $ostype = 'Windows10_64'}
if ($select -eq 2) {$osName = 'Windows'; $osNumber ='11'; $ostype = 'Windows11_64'}
Switch ($select)
{
1 {Invoke-Command $vmCreation}
2 {Invoke-Command $vmCreation}
}
}
While ($select -ne 6)
But we get the following error when running the command directly from a PowerShell console:
That’s because when dealing with not the PowerShell Integrated Console. PowerShell just throws the text in the editor into the terminal window.
With the PowerShell Integrated Console (such as Windows PowerShell ISE), it did something differently (sending a message behind the scenes with the full script to make sure the full script gets run). We can do this because it’s Integrated.
That’s why you got the error when run at the command prompt, but when run in a script it should work fine.
To fix it, we need to change the code a little bit. PowerShell seems to consider the else block as separate statement, not attached to if. Modified the code to use the end of the if and else in the same line.
As you can see, now your script can be run from command prompt without any error.
And it should be run in script mode as well.
Not a reader? Watch this related video tutorial: