You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何识别已挂载的外接存储卷?解决同名内外存储卷区分问题

解决方案

你当前的问题根源是仅使用本地化卷名作为唯一识别依据,而macOS允许重名存储卷存在,重名外接卷挂载时会自动在挂载路径后追加数字后缀避免冲突,我们可以改用唯一性更高的属性组合来识别卷。

核心识别逻辑优化

NSWorkspace 存储卷通知的 userInfo 中除卷名外,还提供多个无重复的属性可以使用:

  • NSWorkspaceVolumeURLKey:卷的挂载路径,重名卷会自动追加后缀,全局唯一
  • NSWorkspaceVolumeIsRemovableKey:布尔值,可直接区分内置(false)和外接(true)存储
  • NSWorkspaceVolumeUUIDKey:卷的硬件唯一标识符,格式化后固定不变,是最可靠的识别依据

优化后代码示例

-- 全局变量,存储所有已挂载外接卷的信息,可绑定到自定义UI控件
property globalRemovableVolumesList : {}

on volumeMounted:aNotification
    set userInfo to aNotification's userInfo
    -- 提取卷的唯一属性
    set volumeName to (NSWorkspaceVolumeLocalizedNameKey of userInfo) as text
    set volumePath to (NSWorkspaceVolumeURLKey of userInfo) as text
    set isRemovable to (NSWorkspaceVolumeIsRemovableKey of userInfo) as boolean
    set volumeUUID to (NSWorkspaceVolumeUUIDKey of userInfo) as text
    
    -- 识别特定名称的外接卷(解决重名区分问题)
    if volumeName is "Macintosh HD" and isRemovable then
        log "外接同名卷已挂载,路径:" & volumePath & " UUID:" & volumeUUID
        -- 此处写对应挂载处理逻辑
    end if
    
    -- 记录所有外接卷到全局列表,供UI调用
    if isRemovable then
        copy {name:volumeName, path:volumePath, uuid:volumeUUID} to end of globalRemovableVolumesList
    end if
end volumeMounted:

on volumeUnmounted:aNotification
    set userInfo to aNotification's userInfo
    set volumeUUID to (NSWorkspaceVolumeUUIDKey of userInfo) as text
    set isRemovable to (NSWorkspaceVolumeIsRemovableKey of userInfo) as boolean
    
    -- 卸载时用UUID匹配,从全局列表移除对应项
    if isRemovable then
        repeat with i from 1 to count of globalRemovableVolumesList
            if uuid of item i of globalRemovableVolumesList = volumeUUID then
                delete item i of globalRemovableVolumesList
                exit repeat
            end if
        end repeat
    end if
end volumeUnmounted:

自定义UI卸载功能实现

点击卸载按钮时,直接使用对应卷的UUID或路径执行卸载命令,完全避免重名干扰:

-- 用UUID卸载(最稳妥)
on unmountVolumeByUUID:volumeUUID
    do shell script "diskutil unmount " & quoted form of ("UUID=" & volumeUUID)
end unmountVolumeByUUID:

-- 用挂载路径卸载
on unmountVolumeByPath:volumePath
    do shell script "diskutil unmount " & quoted form of POSIX path of volumePath
end unmountVolumeByPath:

内容的提问来源于stack exchange,提问作者TheOnlyOneHere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:06:06