PowerShell: Failing to Unregister Machine

Discussion about using the VirtualBox API, Tutorials, Samples.
Post Reply
BullWorth
Posts: 3
Joined: 30. Aug 2014, 04:22

PowerShell: Failing to Unregister Machine

Post by BullWorth »

Hi there, im having issues creating a function to unregister a virtualbox machine.

Code: Select all

## Remove New VirtualBox Machine
Function Remove-VirtualBoxMachine{

    ## CleanupMode
    $CleanupMode = "DetachAllReturnHardDisksOnly"

    $VBTestMachine = $VBOX.FindMachine("VBOXTestName")

    ##Unregister & DeleteConfig'

    #[string[]]$IMedium = @()
    #$IMedium = $VBTestMachine.Unregister("DetachAllReturnHardDisksOnly")
    [string[]]$IMedium = $VBTestMachine.Unregister("DetachAllReturnHardDisksOnly")
    
    $VBTestMachine.DeleteConfig($IMedium)
}
Im having problems getting the safearray, does anyone know how to get it ..... ?

These are its errors:

Code: Select all

Exception calling "Unregister" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"At H:\Windows PowerShell\PS-VirtualBox\V
box testfiles\MyVirtualBoxModule5.ps1:71 char:5
+     [string[]]$IMedium = $VBTestMachine.Unregister("DetachAllReturnHardDisksOnly ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation
 
Exception calling "DeleteConfig" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"At H:\Windows PowerShell\PS-VirtualBox
\Vbox testfiles\MyVirtualBoxModule5.ps1:77 char:5
+     $VBTestMachine.DeleteConfig($IMedium)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation
I was able to create and register a machine with the following:

Code: Select all

[string[]]$VM_GROUPS = @()
$NewMachine = $VBOX.CreateMachine("", "VBOXTestName", $VM_GROUPS, "Windows7_64", "UUID=$Guid")
It turns out, providing a safearray was easier then getting one. although i had some help from a post from a guy having same issue.
and theres another post where a guy is having problems also getting the machine unregistered.
Both are on these forum, but im not able to post links.

My issue lies in getting the safearray returned by the unregister function, any one have a clue how to format the safearray object IMEDIUM within powershell.
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Re: PowerShell: Failing to Unregister Machine

Post by noteirak »

Seems like you're having the same issue as this one.
The person did create a post on the dev mailing list. I'll try to find some archives about it and post back tonight. Feel free to do the same if you have some time to spare but I remember that the solution was found.
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
BullWorth
Posts: 3
Joined: 30. Aug 2014, 04:22

Re: PowerShell: Failing to Unregister Machine

Post by BullWorth »

Hi sorry for not responding that long ...

Yeah i came accross that article too and i thought the same, would be nice to have a solution tho.

Currently im trying to build a powershell module that will work with Virtualbox and i come accross alot of peculiar bugs,
mostly related to the singular instance of the virtualbox interface itself and or getting instances of sessions that were created by virtualbox.

This module works with virtualbox and many functions work but there are many sideeffects too, mainly because IVirtualbox is implemented as a singleton im guessing.
Also when a session is created by virtualbox it seems impossible to get an instance of that.

This is a bug i came accross today.

Im building a function that will mount a harddrive to the first available port on the SATA Controller.
This function will work as long as the machine and controllerport are created by powershell.
When I Create a machine with the virtualbox manager itself the function will fail !!

This is very weird bug, seems also be related to singleton instances.

Exception calling "AttachDevice" with "5" argument(s): "The port and/or device parameter are out of range: port=1 (must be in range [0, 0]), device=0 (must be in range [0, 0])"

Code: Select all


<#
.Synopsis
   Mounts a Harddisk File to a Virtualbox Machine.

.DESCRIPTION
   This will mount a harddisk file (eg. vdi, vhd, etc) to the first available port on the SATA Controller.

.EXAMPLE
   PS C:\> Mount-VirtualBoxHardDisk -File D:\imagefile.vhd -Name testmachine

.NOTES
    If the Machine is made by virtualbox itself we get errors when we try to mount a disk to the second port.
    Exception calling "AttachDevice" with "5" argument(s): "The port and/or device parameter are out of range: port=1 (must be in range [0, 0]), device=0 (must be in range [0, 0])"
    If we make a virtualbox with the powershell function we dont get this error ....
    It evens goes so far that if we create a vbox machine with the ps function but without creating controllerports 
    and then we add them controllerport (SATA) with the vbox manager itself we get same error ...

#>

Function Mount-VirtualBoxHardDisk {

    [CmdletBinding()]
    Param(

        # Machine Name Parameter
        [Parameter(Mandatory=$true,Position=0,HelpMessage="Enter a virtual machine name.")]
        [ValidateNotNullorEmpty()]
        [String]$Name,

        # Harddisk File Path
        [Parameter(Mandatory=$true,Position=0,HelpMessage="Enter full  path to the harddisk file.")]
        [ValidateNotNullorEmpty()]
        [String]$File

    )

    Begin {}

    Process {

        ## Get Machine
        Try { $Machine = $VBOX.FindMachine($Name) }
        Catch { Return $_.Exception.Message }

        ## Create Session Object
        Try { $Session = New-Object -ComObject VirtualBox.Session }
        Catch { Return $_.Exception.Message }


        If ($Machine.State -eq $VBE.MachineState.PoweredOff){
            
            ## Get Object to Medium
            Try {$Medium = $VBOX.OpenMedium($File,$VBE.DeviceType.HardDisk,$VBE.AccessMode.ReadWrite,$false)}
            Catch { Return $_.Exception.Message }

            ## Set Machine Lock Status to Write
            Try { $Machine.lockMachine($Session,$VBE.LockType.Write) }
            Catch { Return $_.Exception.Message }

            ##----------------------------------

            <# Check if there is an available port#>

            ## Get all attachments of Sata Controller
            Try { $MediumAttachments = $Machine.getMediumAttachmentsOfController("SATA")}
            Catch { Return $_.Exception.Message }

            ## Get available port
            [Long]$aPort = $MediumAttachments.Count

            ## There can be only 30 (0-29) 
            If ($aPort -eq 30){ Write-Error -Message "No port available for mounting the disk ..."; Return }


            ## Attach Harddisk to Machine
            Try { $Session.machine.attachDevice("SATA",$aPort,0,$VBE.DeviceType.HardDisk,$Medium) } 
            Catch { Return $_.Exception.Message }

            ##----------------------------------

            ## Save Machine Setting
            Try{ $Session.Machine.SaveSettings() } 
            Catch{ Return $_.Exception.Message }

            ## Unlock Machine
            $Session.UnlockMachine()

        } Else { Write-Error -Message "Cannot Mount Harddisks to Machines that are Not 'PoweredOff' ... " }

    } ## END Process

    End {}
}

BullWorth
Posts: 3
Joined: 30. Aug 2014, 04:22

Re: PowerShell: Failing to Unregister Machine

Post by BullWorth »

Another thing is that I Cannot Revoke a 'SaveState' of a machine when the 'SaveState' is set by virtualbox.
When Virtualbox puts a machine in 'SaveState it also uses a session for that.
It seems i need that exact session to discard the save state it was put in by virtualbox.

I Think Virtualbox uses a WriteLock for that and I cannot use a SharedLock for Discarding the 'SaveState'.
On the other hand I can use a SharedLock to startup a machine that was previously saved by Virtualbox.

Theres so many things (peculiarities) i see when trying to build a module for virtualbox in powershell, i dont know where to mention all these facts, and maybe im already trying todo the same as the other guy ... lol
maybe someone can give me some lead on where to mention all these bugs
Post Reply