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

如何在AppleScript执行结果中搜索指定字符串?

如何在Box Sync菜单栏菜单中搜索目标字符串

嘿,我来帮你搞定这个判断目标字符串是否存在的需求!你已经成功获取到了Box Sync菜单栏的菜单项目列表,接下来只需要提取菜单项目的名称,再做字符串检查就可以了。

问题分析

你当前的脚本返回的是菜单项目对象(比如menu item "Files Synced" of ...),而不是纯字符串,直接拿字符串去匹配肯定行不通。我们需要先把每个菜单项目的name属性提取出来,形成一个纯字符串列表,再进行判断。

完整实现脚本

下面是修改后的脚本,包含获取菜单名称列表、搜索目标字符串的完整逻辑:

-- 先检查Box Sync是否在运行
if application "Box Sync" is not running then
    display dialog "Box Sync 未运行,请先启动应用!"
    return
end if

tell application "System Events"
    tell process "Box Sync"
        tell menu bar item 1 of menu bar 2
            click -- 展开菜单(部分应用需要点击后才能读取菜单内容)
            set menuItems to menu items of menu 1
            -- 提取所有菜单项目的名称,处理无名称的项目(设为空字符串)
            set menuNames to {}
            repeat with anItem in menuItems
                try
                    set end of menuNames to name of anItem
                on error
                    set end of menuNames to ""
                end try
            end repeat
        end tell
    end tell
end tell

-- 定义你要搜索的目标字符串
set targetString to "Pause"

-- 精确匹配:判断目标字符串是否存在于菜单列表中
if menuNames contains targetString then
    display dialog "✅ 找到目标字符串:" & targetString
else
    display dialog "❌ 未找到目标字符串:" & targetString
end if

关键细节说明

  • 提取菜单名称:通过repeat循环遍历每个菜单项目,用name of anItem获取名称;同时用try/on error处理那些没有名称的项目(比如你结果里的menu item 2),避免脚本报错中断。
  • 模糊搜索可选:如果你需要模糊匹配(比如检查是否包含某个子字符串),可以替换判断逻辑为:
    set isFound to false
    set matchedName to ""
    repeat with aName in menuNames
        if aName contains targetString then
            set isFound to true
            set matchedName to aName
            exit repeat
        end if
    end repeat
    if isFound then
        display dialog "✅ 找到匹配项:" & matchedName
    else
        display dialog "❌ 未找到匹配的字符串"
    end if
    
  • 关于click操作:Box Sync的菜单栏菜单通常需要先点击展开才能读取内容,所以脚本里保留了这一步;如果测试发现不需要点击就能获取菜单,可以直接删除click行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:14:35