# v253 helper: disconnect the MN103S/GDR user-mode iSCSI target and optionally remove stale matching CD-ROM devnodes.
# Run PowerShell as Administrator.
param(
    [Alias('Address','Host','Portal','TargetPortalAddress')]
    [string]$PortalAddress = '192.168.0.8',
    [int]$PortalPort = 3260,
    [string]$TargetName = 'iqn.2026-06.local.mn103s:gdr8050l',
    [switch]$RemoveStaleCdromDevices
)
$ErrorActionPreference = 'Continue'

Write-Host "Disconnecting sessions for $TargetName ..."
Get-IscsiSession -ErrorAction SilentlyContinue | Where-Object { $_.TargetNodeAddress -eq $TargetName } | ForEach-Object {
    Write-Host "Disconnect-IscsiTarget SessionIdentifier=$($_.SessionIdentifier)"
    Disconnect-IscsiTarget -SessionIdentifier $_.SessionIdentifier -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
}
Start-Sleep -Milliseconds 500

Write-Host "Removing portal $PortalAddress`:$PortalPort ..."
Remove-IscsiTargetPortal -TargetPortalAddress $PortalAddress -TargetPortalPortNumber $PortalPort -Confirm:$false -ErrorAction SilentlyContinue | Out-Null

Write-Host ''
Write-Host 'Remaining matching iSCSI sessions:'
Get-IscsiSession -ErrorAction SilentlyContinue | Where-Object { $_.TargetNodeAddress -eq $TargetName } | Format-List

Write-Host ''
Write-Host 'Matching CD-ROM PnP devices:'
$cdroms = @(Get-PnpDevice -Class CDROM -ErrorAction SilentlyContinue | Where-Object { $_.InstanceId -like 'SCSI\CDROM&VEN_HL-DT-ST&PROD_DVD-ROM_GDR8050L*' })
$cdroms | Format-Table -AutoSize Status,Class,FriendlyName,InstanceId

if ($RemoveStaleCdromDevices) {
    Write-Warning 'Removing matching HL-DT-ST DVD-ROM GDR8050L PnP device instances via pnputil. Use only for emulator-created stale devices.'
    foreach ($d in $cdroms) {
        Write-Host "pnputil /remove-device `"$($d.InstanceId)`""
        pnputil /remove-device "$($d.InstanceId)"
    }
}

Write-Host ''
Write-Host 'Storage rescan may help Windows drop stale drive letters:'
Write-Host '  Get-PnpDevice -Class CDROM | ? InstanceId -like ''SCSI\CDROM&VEN_HL-DT-ST&PROD_DVD-ROM_GDR8050L*'''
Write-Host '  Or rerun this script with -RemoveStaleCdromDevices after confirming they are emulator-created.'

Write-Host ''
Write-Host 'v253 note: after the single-LUN target fix, only one present GDR8050L CD-ROM should remain after reconnect.'
