Skip to content

Instantly share code, notes, and snippets.

@Timberfang
Created August 12, 2023 13:53
Show Gist options
  • Save Timberfang/a134916ae290b8479300047d87a0d3ce to your computer and use it in GitHub Desktop.
Save Timberfang/a134916ae290b8479300047d87a0d3ce to your computer and use it in GitHub Desktop.
Wait for optical media to be inserted (DVD, Blu-Ray, CD, etc.), then end the function.
function Wait-Disc {
[CmdletBinding()]
param (
[Parameter()]
[int]
$DriveIndex = 0
)
# Derive drive letter
$DriveLetter = ($DriveInfo | Select-Object -ExpandProperty Drive)[$DriveIndex]
# Create a WMI query to monitor the optical drive
$WMIQuery = "SELECT * FROM __InstanceModificationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_CDROMDrive' AND TargetInstance.Drive = '$DriveLetter'"
# Create a management scope and event watcher
$ManagementScope = New-Object System.Management.ManagementScope("\\.\root\cimv2")
$ManagementScope.Connect()
$EventWatcher = New-Object System.Management.ManagementEventWatcher
$EventWatcher.Query = New-Object System.Management.WqlEventQuery($WMIQuery)
$EventWatcher.Scope = $ManagementScope
# Define the event handling script block
$EventHandler = {
$WMIEvent = $event.SourceEventArgs.NewEvent
$WMIDrive = $WMIEvent.TargetInstance
if ($WMIDrive.MediaLoaded) {
Write-Host "Disc detected in drive $DriveLetter"
$EventWatcher.Stop()
}
}
# Register the event handler, hiding its output.
Register-ObjectEvent -InputObject $EventWatcher -EventName EventArrived -Action $EventHandler | Out-Null
Write-Information -InformationAction Continue "Waiting for a new disc to be inserted..."
# Start listening for events
$EventWatcher.Start()
# Wait for the event handler to stop the watcher
$EventWatcher.WaitForNextEvent() | Out-Null
# Unregister the event handler
Unregister-Event -SourceIdentifier $EventWatcher.Name | Out-Null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment