Skip to content

Remove-HyperVVMDvdDrive

Hyper-V: Removes a virtual DVD drive from a virtual machine

#Requires -Version 5.1
#Requires -Modules Hyper-V

[CmdletBinding()]
Param (
    [string]$ComputerName = "localhost",

    [PSCredential]$Credential,

    [Parameter(Mandatory = $true)]
    [string]$Name,

    [Parameter(Mandatory = $true)]
    [int]$ControllerNumber,

    [Parameter(Mandatory = $true)]
    [int]$ControllerLocation
)

Process {
    try {
        $params = @{
            'ComputerName' = $ComputerName
            'ErrorAction'  = 'Stop'
        }
        if ($Credential) { $params.Add('Credential', $Credential) }

        $vm = Get-VM @params | Where-Object { $_.Name -eq $Name -or $_.Id -eq $Name }

        if (-not $vm) {
            throw "Virtual machine '$Name' not found on '$ComputerName'."
        }

        $dvdDrive = Get-VMDvdDrive -VM $vm | Where-Object { 
            $_.ControllerNumber -eq $ControllerNumber -and 
            $_.ControllerLocation -eq $ControllerLocation 
        }

        if (-not $dvdDrive) {
            throw "No DVD drive found on controller $ControllerNumber at location $ControllerLocation for VM '$Name'."
        }

        Remove-VMDvdDrive -VMDvdDrive $dvdDrive -ErrorAction Stop

        $result = [PSCustomObject]@{
            VMName             = $vm.Name
            ControllerNumber   = $ControllerNumber
            ControllerLocation = $ControllerLocation
            Action             = "DvdDriveRemoved"
            Status             = "Success"
            Timestamp          = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }

        Write-Output $result
    }
    catch {
        throw
    }
}

Specifies the name of the Hyper-V host. Defaults to the local machine.

Specifies the credentials to use for the remote connection.

Specifies the name or ID of the virtual machine.

Specifies the controller number.

Specifies the location on the controller.

An interactive directory of PowerShell scripts.