如何使用applescript查找文件夹

时间:2017-04-29 02:17:11

标签: applescript

我试图让applecript找到一个文件夹然后最终使用Preview打开其中的每个项目。我可以预览打开文件夹,但它打开了错误的文件夹。这就是我到目前为止所做的:

    set dFolder to "/Users/bobsmith/Desktop/screencapture"
    tell application "Preview"
open every item of dFolder
end tell

我认为我至少应该能够在调试器中看到该文件夹​​的内容,但我不这样做。

tell application "Finder"
set dFolder to files of folder POSIX file "/Users/bobsmith/Desktop/screencapture" as alias list

告诉

3 个答案:

答案 0 :(得分:2)

我结合了你的两个脚本,它对我有用...(我怀疑预览并没有像传递一个字符串,你的第一行正在做什么?)

set myFiles to missing value
tell application "Finder"
    set myFiles to files of folder POSIX file "/Users/bobsmith/Desktop/screencapture" as alias list
end tell

tell application "Preview"
    open every item of myFiles
end tell

答案 1 :(得分:1)

您需要做的只是省略every item of

set dFolder to "/Users/bobsmith/Desktop/screencapture"
tell application "Preview"
  activate
  open dFolder
end tell

注意:健壮性需要activate:莫名其妙地,从macOS 10.12.4开始,如果Preview尚未运行,则命令很安静无操作。

或者,在概括和简化的重新制定中:

tell application "Preview"
  activate
  open POSIX path of (path to desktop) & "screencapture"
end tell

请注意,这将:

  • 以递归方式打开目标文件夹中的文件;即,不只是在目标文件夹本身,而是在整个文件夹子树

  • 单个文档窗口中打开所有文件(通常)。

说明:

  • path to desktop评估为代表当前用户桌面的文件系统alias
  • POSIX path ofalias转换为POSIX风格的路径,包括尾随/;例如:/Users/bobsmith/Desktop/

  • 字符串附加screencapture&因此会产生类似/Users/bobsmith/Desktop/screencapture

  • 的内容
  • Preview显然理解POSIX文件夹路径(在macOS 10.12上验证),并隐式打开位于指定文件夹及其子树中的所有文件。

直接使用POSIX路径字符串的一个缺点是,安静地预览忽略不存在的路径。
如果您想事先验证目标文件夹是否存在

# This statement will fail, if the resulting path doesn't exist.
set fldr to alias (POSIX path of (path to desktop) & "screencapture" as POSIX file)

tell application "Preview"
    activate
    open fldr
end tell

至于您尝试的内容

由于dfolder被定义为字符串every item枚举该字符串的个别字符

如果在脚本编辑器中运行以下命令:

set dFolder to "/foo/bar"
tell application "Preview"
  every item of dFolder
end tell

您将在“结果”窗格中看到以下内容(封闭的tell application "Preview"块是偶然的):

{"/", "f", "o", "o", "/", "b", "a", "r"}

答案 2 :(得分:0)

me newbee - 我的解决方案:(坏的黑客但有效) 输入是文件列表。将输出存储在变量中并稍后使用。

on run {input, parameters}
    
    #input consists of several files
    #extract from list first file w path
    set myfile to first item of input as string
    #reverse file w path 
    set elifeym to reverse of characters of myfile as text
    #find first :  
    set theTrimLength to offset of ":" in elifeym
    #trim from : until the end of the string
    set theText to characters (theTrimLength) thru -1 of elifeym as string
    #reverse again
    set mypath to reverse of characters of theText as text
    #create link to mypath as alias (if you don't, Automator crashed, when using the folder text 
    set myfolder to alias mypath
    # nothing of this worked for me.... reason unknown
    #set mypath to (get folder of myfile) as string
    #set mypwd to POSIX path of myfile
    
    return myfolder
end run