Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Macos JXA:移动或复制文件_Macos_Applescript_Osx Yosemite_Javascript Automation - Fatal编程技术网

Macos JXA:移动或复制文件

Macos JXA:移动或复制文件,macos,applescript,osx-yosemite,javascript-automation,Macos,Applescript,Osx Yosemite,Javascript Automation,我正在尝试做一件非常简单的事情——使用OS X Yosemite引入的自动化JavaScript移动(或复制)一个文件 到目前为止,我有类似的东西 finder = Application("Finder") finder.move(Path("/Users/user/Source/file.pdf"), { to: Path("/Users/user/Destination/file.pdf"), replacing: true }) 结果不是很好 Error -1728:

我正在尝试做一件非常简单的事情——使用OS X Yosemite引入的自动化JavaScript移动(或复制)一个文件

到目前为止,我有类似的东西

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.

当然,我可以使用类似于
doshelscript(“mv source destination”)
的东西,但是Finder+JAX解决方案似乎更好。

是的,JXA和Finder太乱了。我认为问题在于查找程序喜欢别名等,而不是JavaScript中的非类型变量。首先我想,问题是目标文件不存在,然后调用
Path()
-无法返回变量类型
文件
。但是,即使使用该名称创建空的目标文件,脚本也会失败(但会显示另一条错误消息…)

我发现的唯一方法是在JXA发行说明中使用JXA ObjC桥作为描述符:

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脚本更优雅的方式,但这只是一种感觉;-)


干杯,Michael/Hamburg

此脚本使用带有移动命令的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 })

它也适用于复制命令。

Finder的
move
duplicate
操作对JXA
Path
对象很有效。代码失败的原因是这些操作所期望的
to
参数是在提供文件的路径时指向文件夹的路径。这将有助于:

finder = Application("Finder")

finder.move(Path("/Users/user/Source/file.pdf"), {
    to: Path("/Users/user/Destination/"),
    replacing: true
})

是的,真是太遗憾了。事实上,我至少有另一个代码可以工作:
应用程序(“Finder”).duplicate(路径(“/Users/user/Source/file.pdf”)
将创建一个名为
文件copy.pdf
的文件。另一个
应用程序(“Finder”).duplicate(路径(“/Users/user/Source/file.pdf”),{to:Path(“/Users/user/Destination/file.pdf”)}
将失败,出现
错误-1728:无法获取对象
。看起来目标路径有问题。它是:目标路径需要是文件夹的路径,而不是文件的路径(
mv
语义在这里不适用)。请参阅。尽管Finder使用了不同的路径表示模型,但它可以强制AppleScript别名及其JXA等价物,即路径对象。问题是OP提供了一个文件的路径,他们应该提供一个文件夹的路径。看见