Applescript: How to open a file using the default program?

In applescript, I get one file path that I have to open.

The path to the file is in the format /Users/xxx/my/file/to/open.xyz .

I want to open it using the default program. If it is AVI, I need to open it with a video program, if it is xls, with excel, ...

I tried several things without success:

 --dstfile contains the previous path tell application "Finder" activate open document dstfile end tell 

-> I get error 1728 telling me that he could not get the document

 tell application "Finder" activate open document file dstfile end tell 

-> same thing here

 tell application "Finder" activate open document POSIX file dstfile end tell 

-> same thing here

I am sure that the file exists because I do this before executing this code:

 if not (exists dstfile) then display dialog "File isn't existing" end if 

I cannot use synthax open.xyz from of ... because I get this as a parameter.

Please help me in despair: '(

The answer . Based on the answers, I get the following:

 set command to "open " & quoted form of dsturl do shell script command 
+8
scripting applescript
source share
2 answers

Your problem here is twofold:

  • your path in POSIX notation, which AppleScript cannot force to an alias or file acceptable to Finder, since they will be implicitly created from path strings in HFS notation ( Users:xxx:my:file:to:open.xyz ). Expressly declaring your path as a POSIX file will solve this. Nevertheless,
  • your Finder call prefixes the document to the path, but the AppleScript Finders dictionary does not contain the type of the document object (there is a document object, but it is a child of the finder element that cannot be created in this call). Removing this part will help solve the problem.

TL; DR: the following line will open the file specified through the POSIX path in the default program, without accessing the shell:

 tell application "Finder" to open POSIX file "/Users/xxx/my/file/to/open.xyz" 

Caution: this is the simplest solution, but it will only work for qualified POSIX paths (i.e. those starting with / ), as in the question. Processing relative (for example, paths starting with ~ , . Or .. ) OTOH requires either the AppleScript-ObjectiveC API (not quite trivial) or the shell (enjoy your quotation).

+14
source share

Try:

 set dstfile to "~/xxx/my/file/to/open.xyz" do shell script "open " & dstfile & "" 
0
source share