Search code examples
powershellvirtualbox

PowerShell error in VBoxManage unregistervm --delete


Why does the try part work fine, but catch part gives an error? Weird thing is that even though it gives an error, it still does the deletion. Any ideas?

# Set VRAM size
try {
 Write-Host -nonewline "Setting VRAM size: $($vramsize) MB.. "
 C:\"Program Files"\Oracle\VirtualBox\VBoxManage modifyvm "$vmname" --vram $vramsize
 Write-Host -foregroundcolor green "OK."
}
catch {
 C:\"Program Files"\Oracle\VirtualBox\VBoxManage unregistervm --delete $vmname
 Write-Host -foregroundcolor red "!!! $_.Exception.Message"
 write-error "Fatal: Failed to set VRAM size."
 exit 1
}

Here's the error:

C:\Program Files\Oracle\VirtualBox\VBoxManage : 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
At C:\program files\kulo\files\temp\ubu.pxe.boot.ps1:380 char:2
+  C:\"Program Files"\Oracle\VirtualBox\VBoxManage unregistervm --delet ...
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (0%...10%...20%....0%...90%...100%:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Solution

  • As you can see in your error output, PowerShell tries to execute the output of the following line:

    C:\"Program Files"\Oracle\VirtualBox\VBoxManage unregistervm --delete $vmname
    

    which is some text like 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%, that PowerShell cannot execute. It is no problem in your try block, because there, VBoxManage does not generate any output.

    Anyway, your try and catch blocks won't work on calls like this. You need PowerShell cmdlets that throw exceptions that you can then catch. If you call external programs, you have to evaluate their exit code. I suggest the following solution according to your example:

    Write-Host "Setting VRAM size: $vramsize MB... " -NoNewline
    $process = Start-Process 'C:\Program Files\Oracle\VirtualBox\VBoxManage.exe' -ArgumentList "modifyvm `"$vmname`" --vram $vramsize" -Wait -PassThru
    if ($process.ExitCode -eq 0) {
        Write-Host "OK." -ForegroundColor Green 
    } else {
        Write-Host "NOT OK." -ForegroundColor Red
        Start-Process 'C:\Program Files\Oracle\VirtualBox\VBoxManage.exe' -ArgumentList "unregistervm --delete `"$vmname`""
        Write-Error "Fatal: Failed to set VRAM size."
        exit 1
    }
    

    I tested it with $vramsize=128 for the successful case and $vramsize=512 for the erroneous case.