我正在尝试做一个非常简单的事情 - 使用OS X Yosemite引入的JavaScript for Automation移动(或复制)一个文件。
到目前为止,我有类似的事情。
finder = Application("Finder")
finder.move(Path("/Users/user/Source/file.pdf"), {
to: Path("/Users/user/Destination/file.pdf"),
replacing: true
})
结果并不好。
Error -1728: Can't get object.
当然我可以使用类似doShellScript("mv source destination")
的东西,但Finder + JAX解决方案似乎更好。
答案 0 :(得分:1)
Finder的move
和duplicate
操作可以与JXA Path
对象一起使用。在您提供文件的路径时,您的代码失败的原因是这些操作所期望的to
参数是文件夹的路径。这将有效:
finder = Application("Finder")
finder.move(Path("/Users/user/Source/file.pdf"), {
to: Path("/Users/user/Destination/"),
replacing: true
})
答案 1 :(得分:0)
是的,它与JXA和Finder混乱不堪。我认为问题在于Finder喜欢Aliasses等对抗JavaScript中的非常规变量。首先我想,问题是目标文件不存在,然后Path()
- 调用无法返回变量类型file
。但即使您使用该名称创建一个空目标文件,该脚本也会失败(但会显示另一条错误消息......)
我发现的唯一方法是在JXA发行说明中使用JXA-ObjC-Bridge作为描述符:
ObjC.import('Cocoa')
error = $()
fMa = $.NSFileManager.defaultManager
fileMoved = fMa.moveItemAtPathToPathError('/Users/user/Source/file.pdf','/Users/user/Destination/file.pdf', error)
if (!fileMoved) {
$.NSBeep();
// or do something else depending on error.code
}
我认为它比使用shell脚本更优雅,但这只是一种感觉; - )
干杯,迈克尔/汉堡
答案 2 :(得分:0)
此脚本使用Finder对象和移动命令:
var Finder = Application("Finder")
var homeDirectory = Finder.startupDisk.folders["Users"].folders["user"]
var sourceFile = homeDirectory.folders["Source"].files["file.pdf"]
var destinationFolder = homeDirectory.folders["Destination"]
Finder.move(sourceFile, { to: destinationFolder })
它也适用于重复命令。