Trying to get the volume name of the currently mounted CD or DVD

My goal is to get the volume (disk) name of the currently mounted CD or DVD. I have written an Applescript that achieves this goal using a combination of “do shell script” and some text processing of the result of that command. The comments within the script explain how it works. I would like to ask two questions:

  1. Is there a simpler, more direct, and/or more elegant way of getting the volume name than the “do shell script” method I have used? For example, is there a volume or drive property that is unique to optical disks as opposed to hard drives, network drives, flash drives, etc, that would allow me to home in on the volume name directly?

  2. If the answer to #1 is no, then I would like to ask a question about “grepping” (with which I have little expertise). The result of my “do shell script” is a single line of the form

     "   Volume Name:             [i]CD_or_DVD_Disk_Name[/i]"
    
     I have used repeat loops to remove "Volume Name:" and any leading and trailing blanks, because I couldn't figure out the proper grep command that would achieve the same result.  Could someone please suggest a simple grep command that would extract [i]CD_or_DVD_Disk_Name[/i] from the line?
    

Thank you in advance for any help.


-- "drutil status" generates information on the currently mounted CD or DVD, including its "/dev/disk" value
-- The output of "drutil status" is "egrep"ed to obtain that "/dev/disk" value
-- "diskutil info" utilizes that "/dev/disk" value to generate further information on the currently mounted CD or DVD, including its volume name
-- The output of "diskutil info" is "egrep"ed to obtain the line containing that volume name

set s to (do shell script "diskutil info $(drutil status | egrep -ow '/dev/disk[0-9]') | egrep 'Volume Name:'")

-- The following repeat block takes the output from the shell script and finds the offset of the start of the name of the CD or DVD by skipping over "Volume Name:" and any leading blanks

repeat with m from ((offset of "Volume Name:" in s) + 12) to (length of s)
	if text item m of s is not " " then exit repeat
end repeat

-- The following repeat block takes the output from the shell script and finds the offset of the end of the name of the CD or DVD by skipping over any trailing blanks

repeat with n from (length of s) to 1 by -1
	if text item n of s is not " " then exit repeat
end repeat

-- The name of the CD or DVD is then extracted using the starting and ending offsets derived from the repeat blocks

set disk_name to (text items m thru n of s) as text

I use this to identify a CD from among the other volumes

tell application "Finder"
	set cds to {}
	set d to disks
	repeat with aDisk in d
		if size of aDisk < 1.0E+8 then set end of cds to name of aDisk
	end repeat
end tell

:

Thank you for the suggestion. It seems that this will not work for DVDs. It might also run into trouble with flash drives, if I understand it correctly. Any ideas on how to identify DVDs?

Jacques, thank you for your suggestion. It works very well. In the meanwhile, I did work out a “sed” method of extracting the volume name, and it seems to execute more quickly (about 1 second) than the “awk” method (about 5 to 10 seconds):

do shell script "diskutil info $(drutil status | egrep -ow '/dev/disk[0-9]') | egrep 'Volume Name:' | sed -E 's/^( *Volume Name: +)(.+)( *)$/\\2/'"

I take it from the responses of two experts that there is no direct and easy way to get the volume/disk name of a mounted CD or DVD. So it seems that “do shell script” may be the way to go.

I’m having the same problem and, since this is an ancient thread, am wondering, whether anybody has come up with a better way to do this in the meantime?
Just FYI: I’m trying to cook up a script to rip/convert DVDs using HandbrakeCLI. The converted files are supposed to be placed in a folder named after the DVD volume name. Hence the task to fetch the DVD name.

Thanks in advance.

Konrad

P.S.: Just to avoid any copyright discussions, the DVDs I’m converting have been self-produced by myself, live gigs by my band.

EDIT: I just stumbled across the problem of automatically determining the path to the inserted DVD. This works just fine:

tell application "Finder"
	set the_dvd to choose folder -- choose the dvd disk
	set the_dvd to POSIX path of (the_dvd as text)
end tell

But it requires manual work, we don’t want that. :slight_smile:
I don’t want to do it with folder actions, I just want to be able to pop in a DVD and start a script. If I could get this to work, I could probably even extract the name of the DVD from the resulting string, so my above mentioned problem would be addressed, as well. Two birds → one stone! :cool:

I was looking for an AppleScript that would allow me to determine the /dev/disk# of an optical drive with a disc inserted, where the disc was not mounted. (My iTunes occasionally unmounts a CD after I use the “Get Track Names” feature.) With that disk#, I could then mount the disc, all without leaving iTunes, via my added scripts menu. From the above example, I created this:


set disk_number to ""
do shell script "diskutil info $(drutil status | egrep -ow '/dev/disk[1-9]') | egrep 'Device Identifier:' | sed -E 's/^( *Device Identifier: +)(.+)( *)$/\\2/'"
set disk_number to result
try
	tell application "Finder" to do shell script "diskutil mount " & disk_number
end try

A little slow, but effective.

Model: MacBook Pro (mid-2012)
Browser: Safari 537.36
Operating System: macOS 10.13

This simple “System Events” code use to work, but I don’t have a CD Disk at hand to test it with.
So I’m not sure if this code is still usable.


tell application "System Events" to get the name of every disk whose ejectable is true -- All Ejectable Volumes CD's DVD's Floppy Drives etc.

Just tested when I got home, and found it lists all removable volumes including USB drives.
So no good for the original OP’s question, so apologies.

Regards Mark

There are a few pitfalls with the above approach (a variant of an approach from my early scripting days!):

(1) It will fail if more than one optical disk is attached, for instance, one in a built-in optical drive and another in an external USB optical drive.
(2) It returns only the whole-disk device node /dev/disk# (a.k.a., device identifier) of the optical disk, even if the viewable content is present in a slice of the disk /dev/disk#s# (a.k.a., partition), which may be the case depending on how the optical disk was formatted.
(3) The diskutil mount and diskutil unmount commands may fail unpredictably when the command is not applied to the exact device node of the mountable volume, for instance, when the command is issued as diskutil mount /dev/disk# for a volume residing on a disk partition. Unfortunately, the diskutil mountDisk and diskutil unmountDisk commands, advertised as being capable of handling just these situations, may also fail at unpredictable times.

What I have found to work consistently is to apply the diskutil mount and diskutil unmount commands to the exact device node where the mountable volume resides. Specifying just the disk identifier disk# or disk#s# without the /dev/ prefix works equally well, as long as that is the exact location of the mountable volume. The following Bash script takes these considerations into account. It can handle one or more attached optical disks (in the latter case by applying the mount, unmount, or eject command to all attached optical disks). It can also be run without performing any mount action and instead simply returning the volume name, disk identifier, and mount status of all currently attached optical disks:


mountAction=X ## replace X with m for mount, u for unmount, e for eject, or i for information
opticalDiskIDSearchTerm=$( 
	drutil status | 
	egrep -o "disk[0-9]+" | 
	sort -u | 
	tr "\n" "|" | 
	sed -E "s/[|]+$//; s/^/(/; s/$/)/; s/(disk[0-9]+)/\1(s[0-9]+)?/g;" 
) 
osascript -e "tell application \"System Events\" to return (make new property list item with properties {text:(do shell script \"diskutil list -plist\")})'s property list item \"AllDisks\"'s value" | 
egrep -o "$opticalDiskIDSearchTerm" | 
while read opticalDiskID; do 
	opticalDiskInfo=$(diskutil info "$opticalDiskID") 
	isMounted=$(sed -En "/^[[:blank:]]*Mounted:[[:blank:]]*(Yes|No)$/s//\1/p" <<<"$opticalDiskInfo") 
	[[ -z "$isMounted" ]] && continue 
	if [[ ("$mountAction" == "m") && ("$isMounted" == "No") ]]; then 
		diskutil mount $opticalDiskID 
	elif [[ ("$mountAction" == "u") && ("$isMounted" == "Yes") ]]; then 
		diskutil unmount $opticalDiskID 
	elif [[ "$mountAction" == "e" ]]; then 
		diskutil eject $opticalDiskID 
	elif [[ "$mountAction" == "i" ]]; then 
		volumeName=$(sed -En "/^[[:blank:]]*Volume Name:[[:blank:]]*(.*)$/s//\1/p" <<<"$opticalDiskInfo") 
		echo "$volumeName:$opticalDiskID:$isMounted"
	fi 
done 

Here is a step-by-step description of how the Bash script works:

mountAction=X
- Assigns the desired action to the variable mountAction: replace X with m to mount, u to unmount, e to eject, or i to return information on all currently attached optical disks

opticalDiskIDSearchTerm=$(
drutil status |
egrep -o “disk[0-9]+” |
sort -u |
tr “\n” “|” |
sed -E “s/[|]+$//; s/^/(/; s/$/)/; s/(disk[0-9]+)/\1(s[0-9]+)?/g;”
)

- drutil status:
returns a text string embedded in which are the whole-disk device nodes /dev/disk# for all attached optical disks (NOTE: # is used as a placeholder for the actual disk numbers of attached optical disks in the output of the drutil status command); that result is piped via | to:
- egrep -o “disk[0-9]+”:
extracts onto separate lines of text just the disk identifiers (disk#) from the device node entries /dev/disk#; that result is piped via | to:
- sort -u:
removes any duplicate disk# entries (probably an unnecessary step but included for safety’s sake); that result is piped via | to:
- tr “\n” “|”:
transforms the disk# disk identifiers residing on separate lines into a single line of disk identifiers delimited by pipe characters disk#|disk#|…; that result is piped via | to:
- sed -E “s/[|]+$//; s/^/(/; s/$/)/; s/(disk[0-9]+)/\1(s[0-9]+)?/g;”:
(1) strips a trailing pipe character if present
(2) encloses the whole string in left and right parentheses
(3) adds a b?[/b] suffix to each disk identifier entry so that subsequent regular expression searching will match not only whole-disk disk identifiers disk# but also partition disk identifiers disk#s#, making the final form of the string b[/b], one disk#(s[0-9]+)?) entry for each attached optical disk
- opticalDiskIDSearchTerm=$(…):
assigns the regular expression search term that was just created, b[/b], to the variable opticalDiskIDSearchTerm

osascript -e “tell application "System Events" to return (make new property list item with properties {text:(do shell script "diskutil list -plist")})'s property list item "AllDisks"'s value” |
egrep -o “$opticalDiskIDSearchTerm” |
while read opticalDiskID; do
opticalDiskInfo=$(diskutil info “$opticalDiskID”)
isMounted=$(sed -En “/^[[:blank:]]Mounted:[[:blank:]](Yes|No)$/s//\1/p” <<<“$opticalDiskInfo”)
[[ -z “$isMounted” ]] && continue
if [[ (“$mountAction” == “m”) && (“$isMounted” == “No”) ]]; then
diskutil mount $opticalDiskID
elif [[ (“$mountAction” == “u”) && (“$isMounted” == “Yes”) ]]; then
diskutil unmount $opticalDiskID
elif [[ “$mountAction” == “e” ]]; then
diskutil eject $opticalDiskID
elif [[ “$mountAction” == “i” ]]; then
volumeName=$(sed -En “/^[[:blank:]]Volume Name:[[:blank:]](.*)$/s//\1/p” <<<“$opticalDiskInfo”)
echo “$volumeName:$opticalDiskID:$isMounted”
fi
done

- diskutil list -plist:
returns an XML property list whose property list item AllDisks contains a list of the disk identifiers of all (optical and non-optical) attached disks disk# and their partitions disk#s#; this command is serialized and executed via an AppleScript do shell script command so that its results will be properly serialized for the AppleScript command in which the do shell script command is embedded:
- “tell application "System Events" to return (make new property list item with properties {text:(do shell script "diskutil list -plist")})'s property list item "AllDisks"'s value”:
this serialized AppleScript command in which the above diskutil list -plist command is embedded, when executed, transforms the XML property list returned by diskutil list -plist into an AppleScript System Events property list object, from whose AllDisks key the previously described list of disk# and disk#s# disk identifiers is retrieved:
- osascript -e “tell application "System Events" to return (make new property list item with properties {text:(do shell script "diskutil list -plist")})'s property list item "AllDisks"'s value”:
executes the above serialized AppleScript command, and pipes the resulting list of disk# and disk#s# disk identifiers via | to:
- egrep -o “$opticalDiskIDSearchTerm”:
uses the previously constructed regular expression search term opticalDiskIDSearchTerm to extract from the list of disk# and disk#s# disk identifiers just the disk identifiers of attached optical disks, and pipes the result via | to:
- while read opticalDiskID; do…done:
executes the following commands, i.e., those between do and done, on each of the optical disk disk# and disk#s# disk identifiers one at a time:
- diskutil info “$opticalDiskID”:
returns a text string containing information on the current disk or disk volume, including its volume name and mount status (NOTE: the mount status is returned with the basic form of the diskutil info command but not its plist form diskutil info -plist)
- opticalDiskInfo=$(…):
assigns the disk information string that was just retrieved to the variable opticalDiskInfo
- sed -En “/^[[:blank:]]Mounted:[[:blank:]](Yes|No)$/s//\1/p” <<<“$opticalDiskInfo”:
extracts the mount status string from the variable opticalDiskInfo: Yes if the disk or disk volume is mounted, No if it is unmounted, or the empty string if it is unmountable
- isMounted=$(…):
assigns the mount status string that was just retrieved to the variable isMounted
- [[ -z “$isMounted” ]] && continue:
skips the disk or disk volume represented by the current disk identifier if it is unmountable, i.e., if isMounted = the empty string
- if [[ (“$mountAction” == “m”) && (“$isMounted” == “No”) ]]; then
diskutil mount $opticalDiskID
elif [[ (“$mountAction” == “u”) && (“$isMounted” == “Yes”) ]]; then
diskutil unmount $opticalDiskID
elif [[ “$mountAction” == “e” ]]; then
diskutil eject $opticalDiskID
elif [[ “$mountAction” == “i” ]]; then
volumeName=$(sed -En “/^[[:blank:]]Volume Name:[[:blank:]](.*)$/s//\1/p” <<<“$opticalDiskInfo”)
echo “$volumeName:$opticalDiskID:$isMounted”
fi
:
if mountAction = m, u, or e, performs the specified mount action if that action is needed: mounts the disk or disk volume if mount is specified and it is currently unmounted, unmounts if unmount is specified and the disk or disk volume is currently mounted, or ejects whether the disk or disk volume is currently mounted or unmounted
if mountAction = i, extracts the volume name from the variable opticalDiskInfo, and outputs the colon-delimited string [volume name]:[disk identifier]:[mount status]

The following is an AppleScript handler, manageOpticalDisks, that wraps the above Bash script and facilitates its execution. The handler takes as its input argument a single character specifying the desired behavior: “m” to mount, “u” to unmount, “e” to eject", or “i” to return information on currently attached optical disks. If a mount (“m”), unmount (“u”), or eject (“e”) action is specified, the Bash script will be run as a background osascript by grouping all the commands within curly braces and executing the group in the background via a “&>/dev/null &” suffix to the script’s text. This is done so that control may be returned to the calling script immediately after calling the handler without having to wait the sometimes substantial amount of time needed for disk interrogation and the mount action to occur. If the return of information on currently attached optical disks is requested (input argument = “i”), the Bash script will be run in the foreground, its output will be parsed, and a record of the form {volumeNames:[list of volume names], diskIDs:[list of disk identifiers], isMounted:[list of boolean values indicating a volume’s current mount status]} will be returned to the calling program. If there is only one attached volume, the results will be returned as the values themselves rather than as lists of values.


on manageOpticalDisks(mountAction)
	(*
	Input argument mountAction:
		One of the following characters:
			"m"  -  mount any unmounted optical volumes
			"u"   -  unmount any mounted optical volumes
			"e"   -  eject all attached optical volumes
			"i"    -  return volume name, disk identifier, and mount status of all attached optical volumes
	Return value:
		If the input argument = "m", "u", or "e":
			The empty string (i.e., the return value of a background osascript)
		If the input argument = "i":
			A record of the form {volumeNames:[list of volume names], diskIDs:[list of disk identifiers], isMounted:[list of boolean values indicating a volume's current mount status]} for all attached optical disk volumes
			If there is only one attached volume, the results will be returned as the values themselves rather than as lists of values
	*)
	if {mountAction} is not in {"m", "u", "e", "i"} then error "The input argument must be \"m\", \"u\", \"e\", or \"i\"."
	set lf to linefeed
	set shellScript to "mountAction=" & mountAction & lf & ¬
		"opticalDiskIDSearchTerm=$( " & lf & ¬
		"	drutil status | " & lf & ¬
		"	egrep -o \"disk[0-9]+\" | " & lf & ¬
		"	sort -u | " & lf & ¬
		"	tr \"\\n\" \"|\" | " & lf & ¬
		"	sed -E \"s/[|]+$//; s/^/(/; s/$/)/; s/(disk[0-9]+)/\\1(s[0-9]+)?/g;\" " & lf & ¬
		") " & lf & ¬
		"osascript -e \"tell application \\\"System Events\\\" to return (make new property list item with properties {text:(do shell script \\\"diskutil list -plist\\\")})'s property list item \\\"AllDisks\\\"'s value\" | " & lf & ¬
		"egrep -o \"$opticalDiskIDSearchTerm\" | " & lf & ¬
		"while read opticalDiskID; do " & lf & ¬
		"	opticalDiskInfo=$(diskutil info \"$opticalDiskID\") " & lf & ¬
		"	isMounted=$(sed -En \"/^[[:blank:]]*Mounted:[[:blank:]]*(Yes|No)$/s//\\1/p\" <<<\"$opticalDiskInfo\") " & lf & ¬
		"	[[ -z \"$isMounted\" ]] && continue " & lf & ¬
		"	if [[ (\"$mountAction\" == \"m\") && (\"$isMounted\" == \"No\") ]]; then " & lf & ¬
		"		diskutil mount $opticalDiskID " & lf & ¬
		"	elif [[ (\"$mountAction\" == \"u\") && (\"$isMounted\" == \"Yes\") ]]; then " & lf & ¬
		"		diskutil unmount $opticalDiskID " & lf & ¬
		"	elif [[ \"$mountAction\" == \"e\" ]]; then " & lf & ¬
		"		diskutil eject $opticalDiskID " & lf & ¬
		"	elif [[ \"$mountAction\" == \"i\" ]]; then " & lf & ¬
		"		volumeName=$(sed -En \"/^[[:blank:]]*Volume Name:[[:blank:]]*(.*)$/s//\\1/p\" <<<\"$opticalDiskInfo\") " & lf & ¬
		"		echo \"$volumeName:$opticalDiskID:$isMounted\"" & lf & ¬
		"	fi " & lf & ¬
		"done "
	if {mountAction} is in {"m", "u", "e"} then set shellScript to "{ " & shellScript & " } &>/dev/null & "
	set theResult to (do shell script shellScript)
	if mountAction = "i" then
		set {tid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, ":"}
		try
			set {volumeName, diskID, isMounted} to {{}, {}, {}}
			repeat with currResult in (get theResult's paragraphs)
				tell ((currResult as text)'s text items) to set {end of volumeName, end of diskID, end of isMounted} to {first item, second item, (third item) = "Yes"}
			end repeat
			if volumeName's length = 1 then set {volumeName, diskID, isMounted} to {volumeName's first item, diskID's first item, isMounted's first item}
			set theResult to {volumeName:volumeName, diskID:diskID, isMounted:isMounted}
		end try
		set AppleScript's text item delimiters to tid
	end if
	return theResult
end manageOpticalDisks

Here is a version using ApplescriptObjC that will return a list of disks and their format and whether they are ejectable.

Obviously the ejectable ones of a certain format like “ISO 9660” or “Universal Disk Format (UDF)” are CDs or DVDs. But they also might be mounted disk images


use AppleScript version "2.5"
use framework "Foundation"
use scripting additions

property NSURLIsDirectoryKey : a reference to current application's NSURLIsDirectoryKey
property NSURLVolumeIsEjectableKey : a reference to current application's NSURLVolumeIsEjectableKey
property NSURLVolumeIsRemovableKey : a reference to current application's NSURLVolumeIsRemovableKey
property NSURLVolumeLocalizedFormatDescriptionKey : a reference to current application's NSURLVolumeLocalizedFormatDescriptionKey
property NSVolumeEnumerationSkipHiddenVolumes : a reference to current application's NSVolumeEnumerationSkipHiddenVolumes
property NSURLVolumeIsLocalKey : a reference to current application's NSURLVolumeIsLocalKey
property NSURLVolumeNameKey : a reference to current application's NSURLVolumeNameKey
property NSArray : a reference to current application's NSArray
property NSString : a reference to current application's NSString
property |NSURL| : a reference to current application's |NSURL|

set fileManager to current application's NSFileManager's defaultManager()
set diskURLs to fileManager's mountedVolumeURLsIncludingResourceValuesForKeys:(missing value) options:(NSVolumeEnumerationSkipHiddenVolumes)
set diskList to {}
repeat with i from 1 to count diskURLs
	set theSourceURL to item i of diskURLs
	set {theResult, diskFormat, theError} to (theSourceURL's getResourceValue:(reference) forKey:(NSURLVolumeLocalizedFormatDescriptionKey) |error|:(reference))
	if not (theResult as boolean) then error (theError's |localizedDescription|() as text)
	set {theResult, diskName, theError} to (theSourceURL's getResourceValue:(reference) forKey:(NSURLVolumeNameKey) |error|:(reference))
	if not (theResult as boolean) then error (theError's |localizedDescription|() as text)
	set {theResult, diskEjectable, theError} to (theSourceURL's getResourceValue:(reference) forKey:(NSURLVolumeIsEjectableKey) |error|:(reference))
	if not (theResult as boolean) then error (theError's |localizedDescription|() as text)
	set end of diskList to {diskName as text, diskFormat as text, diskEjectable as boolean}
end repeat
return diskList

You can parse thru the list to get the CD/DVDs

EDIT major portions of this code is from Shane’s FileManagerLib
https://latenightsw.com/support/freeware/

@robertfern

It would be useful to add these instructions at the very beginning of your script.

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use scripting additions
----------------------------------------------------------------

I wish to add that the returned list may be wrong.
Here I run an iMac mid 2011 with an internal mechanical hard disk and a SSD in a Thunderbolt enclosure used as the boot volume.
The script returns the list:
{{“SSD 1000”, “APFS”, false}, {“Macintosh HD”, “Mac OS étendu (journalisé)”, false}}

But, if I select “Macintosh HD”, the icon of the internal HD and presse cmd + E, this disk is perfectly ejected.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) jeudi 21 janvier 2021 18:36:20

Oops.

How’d that happen –
I’m usually more thorough.

FIXED

@robertfern

You’re not the first one forgetting the required instructions.

Maybe more interesting are the comments about the returned list.
At this time, the mechanical HD is ejected and of course the result is:
{{“SSD 1000”, “APFS”, false}}.
Yes, the device which was described as not ejectable, is no longer reported.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) jeudi 21 janvier 2021 18:49:36

Try this instead.

There is a second NSURL key NSURLVolumeIsRemovableKey
See if it differs from key NSURLVolumeIsEjectableKey on that volume


use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

property NSURLIsDirectoryKey : a reference to current application's NSURLIsDirectoryKey
property NSURLVolumeIsEjectableKey : a reference to current application's NSURLVolumeIsEjectableKey
property NSURLVolumeIsRemovableKey : a reference to current application's NSURLVolumeIsRemovableKey
property NSURLVolumeLocalizedFormatDescriptionKey : a reference to current application's NSURLVolumeLocalizedFormatDescriptionKey
property NSVolumeEnumerationSkipHiddenVolumes : a reference to current application's NSVolumeEnumerationSkipHiddenVolumes
property NSURLVolumeIsLocalKey : a reference to current application's NSURLVolumeIsLocalKey
property NSURLVolumeNameKey : a reference to current application's NSURLVolumeNameKey

property NSArray : a reference to current application's NSArray
property NSString : a reference to current application's NSString
property |NSURL| : a reference to current application's |NSURL|

set fileManager to current application's NSFileManager's defaultManager()
set diskURLs to fileManager's mountedVolumeURLsIncludingResourceValuesForKeys:(missing value) options:(NSVolumeEnumerationSkipHiddenVolumes)
set diskList to {}
set cdList to {}
repeat with i from 1 to count diskURLs
	set theSourceURL to item i of diskURLs
	set {theResult, diskFormat, theError} to (theSourceURL's getResourceValue:(reference) forKey:(NSURLVolumeLocalizedFormatDescriptionKey) |error|:(reference))
	if not (theResult as boolean) then error (theError's |localizedDescription|() as text)
	set {theResult, diskName, theError} to (theSourceURL's getResourceValue:(reference) forKey:(NSURLVolumeNameKey) |error|:(reference))
	if not (theResult as boolean) then error (theError's |localizedDescription|() as text)
	set {theResult, diskEjectable, theError} to (theSourceURL's getResourceValue:(reference) forKey:(NSURLVolumeIsEjectableKey) |error|:(reference))
	if not (theResult as boolean) then error (theError's |localizedDescription|() as text)
	set {theResult, diskRemovable, theError} to (theSourceURL's getResourceValue:(reference) forKey:(NSURLVolumeIsRemovableKey) |error|:(reference))
	if not (theResult as boolean) then error (theError's |localizedDescription|() as text)
	set {diskName, diskFormat, diskEjectable, diskRemovable} to {diskName as text, diskFormat as text, diskEjectable as boolean, diskRemovable as boolean}
	set end of diskList to {diskName, diskFormat, diskEjectable, diskRemovable}
	
	if diskEjectable and (diskFormat is in {"ISO 9660", "Universal Disk Format (UDF)"}) then
		set end of cdList to {diskName, diskFormat, diskEjectable, diskRemovable}
	end if
end repeat
get NSVolumeEnumerationSkipHiddenVolumes as integer
get cdList
return diskList

My CD/DVD drive is damaged this moment, so I can’t test. By why anyone doesn’t use the on CD/DVD disk appeared handlers? They doesn’t work stable, or they doesn’t work at all? I think, this handlers can be embedded into the main (bigger script) and provide the name of CD/DVD when they appear.
Having the name of CD/DVD for first time, you can check then if CD/DVD is mounted or ejected any time. Using try statements of plain AppleScript. Maybe, I am wrong.