AppleScript Keynote hangup after opening a illegal pptx file - applescript

first I am a beginner AppleScript developer. and I have searched this question for a long time but no result found. I have an AppleScript to convert ppt files into pdf format. but the script will hangup after it matches a bad ppt file.
the script/keynote will popup a dialog showing "xxx.ppt can't be opened right now" "the file format is invalid".
is there any way to prevent keynote from popping up this kinds of dialog?
below is the sample code, and file is a image file but I changed extension to pptx to simulate an illegle file:
set thefile to POSIX file "/Users/dazhangluo/Downloads/brain-storming.pptx"
tell application "Keynote"
activate
try
set thedoc to open thefile
--display dialog class of thedoc
on error errMessage
--display dialog errMessage
log errorMessage
end try
end tell

There is a command-line tool called exiftool which can inspect files and get their metadata, including the 'file type' tag (using -filetype). There are a variety of ways to install it†. Unlike 'mdls', it isn't easily fooled by the file extension. If you run it on a pptx file, it will include this in its results:
File Type : PPTX
You can then grab the last word to test. This script will loop through the files in the specified folder, use exiftool to extract their file type, and then copy the alias of any matching file to a new list. It then opens each file in keynote. My version of keynote (v8) doesn't let me script anything with powerpoint documents, so you're on your own at that point.
set srcFol to (path to desktop as text) & "presentations" as alias
-- or if you prefer…
-- set srcFol to choose folder
tell application "Finder"
set fList to files of srcFol as alias list
set cleanList to {}
repeat with f in fList
set ppFile to POSIX path of f
set qfFile to quoted form of ppFile
tell me to set exifData to do shell script "/usr/local/bin/exiftool -filetype " & qfFile
if last word of exifData is "PPTX" then
set end of cleanList to contents of f
--> alias "Mac:Users:username:Desktop:presentations:powerpoint1.pptx"
end if
end repeat
end tell
tell application "Keynote"
activate
repeat with pptxFile in cleanList
open pptxFile
-- do whatever
end repeat
end tell
NB † Depending upon where exiftool is installed, you may need to change the path, which you can get with which exiftool.

Related

Batch Convert *.numbers to *.csv AppleScript

I was looking for a script that would batch convert all *.numbers files in a given folder to *.csv files.
I found the following on GitHub and added an additional line as suggested in the comments suggestion. When I run the script, Numbers launches and opens the test file from the folder specified - but the file is not exported. Numbers just stays open and terminal errors out with:
/Users/Shared/Untitled.scpt: execution error: Numbers got an error: Invalid key form. (-10002)
The script (located in /Users/Shared) has the following permissions:
-rwxr-xr-x
#!/usr/bin/osascript
on run argv
set theFilePath to POSIX file (item 1 of argv)
set theFolder to theFilePath as alias
tell application "Finder" to set theDocs to theFolder's items
-- Avoid export privilege problem
set privilegeFile to (theFolder as text) & ".permission"
close access (open for access privilegeFile)
repeat with aDoc in theDocs
set docName to aDoc's name as text
if docName ends with ".numbers" then
set exportName to (theFolder as text) & docName
set exportName to exportName's text 1 thru -9
set exportName to (exportName & "csv")
tell application "Numbers"
open aDoc
delay 5 -- may need to adjust this higher
tell front document
export to file exportName as CSV
close
end tell
end tell
end if
end repeat
end run
Any suggestions?
Here is what I did and works for me in macOS High Sierra:
In Terminal:
touch numb2csv; open -e numb2csv; chmod +x numb2csv
• This creates an empty ASCII Text file named numb2csv.
• Opens, by default, numb2csv in TextEdit.
• Makes the numb2csv file executable.
Copy and paste the example AppleScript code, shown further below, into the opened numb2csv file.
Save and close the numb2csv file.
In Terminal executed the numb2csv executable file, e.g.:
./numb2csv "$HOME/Documents"
This created a CSV file of the same name as each Numbers document in my Documents folder, not traversing any nested folders.
Example AppleScript code:
#!/usr/bin/osascript
on run argv
set theFilePath to POSIX file (item 1 of argv)
set theFolder to theFilePath as alias
tell application "System Events" to set theDocs to theFolder's items whose name extension = "numbers"
repeat with aDoc in theDocs
set docName to aDoc's name as text
set exportName to (theFolder as text) & docName
set exportName to exportName's text 1 thru -8
set exportName to (exportName & "csv")
tell application "Numbers"
launch
open aDoc
repeat until exists document 1
delay 3
end repeat
tell front document
export to file exportName as CSV
close
end tell
end tell
end repeat
tell application "Numbers" to quit
end run
NOTE: As coded, this will overwrite an existing CSV file of the same name as each Numbers file processed, if they already exist. Additional coding required if wanting to not overwrite existing files
If you receive the Script Error:
Numbers got an error: The document “name” could not be exported as “name”. You don’t have permission.
It is my experience that the Numbers document was not fully opened prior to being exported and that increasing the value of the delay command resolves this issue. This is of course assuming that one actually has write permissions in the folder the target Numbers documents exists.
Or one can introduce an error handler within the tell front document block which, if my theory is right about the target document not being fully loaded before the export, will give additional time, e.g.:
Change:
tell front document
export to file exportName as CSV
close
end tell
To:
tell front document
try
export to file exportName as CSV
close
on error
delay 3
export to file exportName as CSV
close
end try
end tell
Note: The primary example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. See included example directly above.
I was looking for that, unfortunately, that doesn’t work anymore.
This line
tell application "System Events" to set theDocs to theFolder's items whose name extension = "numbers"
Gets the following error:
execution error: Can’t make file "file.numbers" of application "System Events" into the expected type. (-1700)
macOs Big Sur Versio 11.01
automator version 2.10
Numbers version 10.3.5
Inspired by this thread and those articles Exporting Numbers Documents and Get full directory contents with AppleScript
The following code works:
#!/usr/bin/osascript
log "Start"
property exportFileExtension : "csv"
tell application "Finder"
activate
set sourceFolder to choose folder with prompt "Please select directory."
set fileList to name of every file of sourceFolder
end tell
set the defaultDestinationFolder to sourceFolder
repeat with documentName in fileList
log "documentName: " & documentName
set fullPath to (sourceFolder as text) & documentName
log "fullPath: " & fullPath
if documentName ends with ".numbers" then
set documentName to text 1 thru -9 of documentName
tell application "Finder"
set newExportItemName to documentName & "." & exportFileExtension
set incrementIndex to 1
repeat until not (exists document file newExportItemName of defaultDestinationFolder)
set newExportItemName to ¬
documentName & "-" & (incrementIndex as string) & "." & exportFileExtension
set incrementIndex to incrementIndex + 1
end repeat
end tell
set the targetFileHFSPath to ¬
(defaultDestinationFolder as string) & newExportItemName
tell application "Numbers"
launch
open fullPath
with timeout of 1200 seconds
export front document to file targetFileHFSPath as CSV
end timeout
close
end tell
end if
end repeat
user3439894's answer works with a few change:
exists document 1 => number of documents > 0

Applescript: can't make file "xx" into type <<class fsrf>>

I'm trying to get a script working which is able to batch export .mts format video files via quicktime into .mov files in 1080p. The script fails with the following error: "The action “Run AppleScript” encountered an error: “QuickTime Player got an error: Can’t make file (document "00000.MTS") into type «class fsrf».”". I assume this has something to do with using text file paths? Note I'm not experienced with Applescript and would really appreciate any help to get this simple bit of script working. Currently it's in automator as a service:
on run {inputFiles}
if inputFiles is equal to {} then
set inputFiles to (choose file with prompt "Select the file(s) to convert:" with multiple selections allowed without invisibles)
end if
open inputFiles
end run
on open droppedItems
tell application "Finder" to set inputFolder to (container of first item of droppedItems) as Unicode text
set outputFolder to (choose folder with prompt "Select output folder:" default location (inputFolder as alias)) as Unicode text
set exportPreset to (choose from list {"Movie", "iPhone", "iPod", "480p", "720p", "1080p"} with prompt "Choose QuickTime Export Preset:") as Unicode text
if exportPreset is equal to "false" then
return
end if
repeat with currentItem in droppedItems
repeat until getProcessPercentCPU("CoreMediaAuthoringSessionHelper") is equal to ""
end repeat
tell application "Finder" to set fileName to name of currentItem as Unicode text
set fileName to text 1 thru ((fileName's length) - (offset of "." in ¬
(the reverse of every character of fileName) as text)) of fileName
convertFile(currentItem, outputFolder & fileName & ".mov", exportPreset)
end repeat
end open
on convertFile(inputFile, outputFile, exportPreset)
tell application "QuickTime Player"
set thisMovie to open inputFile
open for access file thisMovie
close access file thisMovie
export thisMovie in (outputFile) using settings preset exportPreset
close thisMovie
end tell
end convertFile
on getProcessPercentCPU(processName)
do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processName & "$/ {print $1}'"
end getProcessPercentCPU
Try changing:
set outputFolder to (choose folder with prompt "Select output folder:" default location (inputFolder as alias)) as Unicode text
to:
set outputFolder to POSIX path of (choose folder with prompt "Select output folder:" default location (inputFolder as alias))
and:
convertFile(currentItem, outputFolder & fileName & ".mov", exportPreset)
to:
set outputFile to POSIX file (outputFolder & fileName & ".mov")
convertFile(currentItem, outputFile, exportPreset)
and remove the open for access/close access commands.
Sandboxed apps don't like receiving path strings to open/save commands, but accept alias/POSIX file values okay. (If it still doesn't work then it's some other issue at play, but that's always the first thing to check when you get a filesystem permissions error as you describe.)
The error occurs because thisMovie is a document reference of QuickTime Player and this class cannot be converted / coerced to a file system reference («class fsrf»).
That's what the error message says
Can’t make file (document "00000.MTS") into type «class fsrf»
The Standard Additions command open for access does not support QuickTime Player documents anyway. What is the purpose of the open / close lines?
Note:
as Unicode text as coercion to string is outdated since macOS 10.5 Leopard. It's only used with read and write commands to handle UTF16 encoded text. A coercion to standard AppleScript text is simply written as text. In case of name of currentItem it's redundant anyway because the class of name is always text.

Applescript CS5 and CS6 export with save for web will not work

I am at my wit's end. I have tried all variations to get this script to work. The error I get is Adobe Photoshop CS6 got an error: Can’t get current document. and the highlighted script error is my "export in file newFileName.." block. I've tried putting alias in different positions, using file, not using file. Also I get this error message, but the actual script seems to stop working right after "set docName to name of docRef"
And basically I just copied this code from another script that was working fine and just changed a save this file... to a export this file...
-- set the folders that you want to use
set inputFolder to choose folder with prompt "Choose the folder of images to downsize."
set pathToDesktop to (path to desktop folder as string)
set outputFolder to pathToDesktop & "PhotoshopRetina:"
tell application "Finder"
set filesList to files in folder inputFolder
if not (exists folder outputFolder) then
make new folder at desktop with properties {name:"PhotoshopRetina"}
end if
end tell
with timeout of 86400 seconds
tell application "Adobe Photoshop CS6"
set display dialogs to never
close every document saving no
end tell
repeat with aFile in filesList
tell application "Finder"
-- The step below is important because the 'aFile' reference as returned by
-- Finder associates the file with Finder and not Photoshop. By converting
-- the reference below 'as alias', the reference used by 'open' will be
-- correctly handled by Photoshop rather than Finder.
set theFile to aFile as string
set theFileName to name of aFile
set theFileInfo to info for alias theFile
if kind of theFileInfo is "Adobe Photoshop JPEG file" then
my retinaDisplay(theFile)
end if
end tell
end repeat
end timeout
end
on retinaDisplay(theFile)
tell application "Adobe Photoshop CS6"
open alias theFile
set docRef to the current document
-- Convert the document to a document mode that supports saving as jpeg
if (mode of docRef is not RGB) then
change mode docRef to RGB
end if
tell docRef
set color profile kind to none
end tell
set infoRef to get info of docRef
set docName to name of docRef
set docBaseName to getBaseName(docName) of me
set newFileName to (my outputFolder as string) & docBaseName & ".jpg"
tell current document
export in file newFileName as save for web with options {class:save for web export options, web format:JPEG, embed color profile:false, quality:45} with copying
end tell
close current document without saving
end tell
end retinaDisplay
-- Returns the document name without extension (if present)
on getBaseName(fName)
set baseName to fName
repeat with idx from 1 to (length of fName)
if (item idx of fName = ".") then
set baseName to (items 1 thru (idx - 1) of fName) as string
exit repeat
end if
end repeat
return baseName
end getBaseName
end
If I open an image in photoshop I can run this code with no errors.
set f to (path to desktop as text) & "test.jpg"
tell application "Adobe Photoshop CS6"
tell current document
export in file f as save for web
end tell
end tell
However, if I additionally add your "with options" code then I get your error. I don't even know what the "with copying" part is. I don't think that means anything to photoshop. So the problem is not with the "current document". The problem is with your options. You must be doing that part wrong.
Good luck.

AppleScript to convert NEF to JPG preserving Creation Date/Time

I have a Nikon camera that outputs great NEF raw files, and not so great JPEG files. I can use the Preview app that came with my Mac OSX 10.6.8 (Snow Leopard) to simply open a NEF and SaveAs JPEG to create a file about 1/6 the size that is virtually indistinguishable from the original NEF.
[EDIT] Here is the final script that works as desired, with comments and some error testing:
(*
AppleScript to convert Nikon raw NEF files into much smaller JPG files.
The JPG files will inherit the file date and time of the source NEF files.
Note that any JPG files in the target folder that have the same name
as a NEF file in that folder, will be overwritten.
*)
-- User selects target folder with NEF files to convert and save there.
set theImageFolder to choose folder with prompt "
Select a folder containing fileⁿ.NEF images to
convert into JPEG images and SaveAs: fileⁿ.JPG"
set theOutputFolder to theImageFolder
-- Finder locates NEF files, ignoring other file types in the target folder.
tell application "Finder"
set theImages to every file of theImageFolder whose name extension is "NEF"
end tell
-- Image Events app processes the images.
tell application "Image Events"
launch
repeat with a from 1 to length of theImages
-- Get file name as text string.
set theImage to file ((item a of theImages) as string)
-- Get date/time of source NEF file.
tell application "Finder" to set fileTimestamp to creation date of theImage
set theImageReference to open theImage
tell theImageReference
set theImageName to name
-- Detect the .NEF extension to replace with .JPG on output.
set savedDelimiters to AppleScript's text item delimiters
-- Split filename string into list, using "." as a delimiter.
set AppleScript's text item delimiters to {"."}
set delimitedList to every text item of theImageName
-- Remove the .NEF extension from the list, if it was there.
ignoring case
--Process only NEF files.
if last item of delimitedList is "NEF" then
set filenameList to items 1 thru -2 of delimitedList
set theImageName to filenameList as string
end if
end ignoring
-- Restore delimiters to default in case it had previously been changed.
set AppleScript's text item delimiters to savedDelimiters
-- Construct full path of file to save, with JPG as output file extension.
set saveImageName to ((theOutputFolder as string) & theImageName & ".JPG")
-- Check if a file with the output JPG file name is already present in the target folder.
tell application "Finder"
if exists file saveImageName then
-- Abort script if user doesn't want to overwrite this file and continue.
beep
if button returned of (display dialog " An identical JPG file is already at:
" & saveImageName & "
Would you like to:" buttons {"Replace it and continue", "Abort"} default button "Abort") is "Abort" then exit repeat
end if
end tell
-- SaveAs the file in JPEG format, leaving the source NEF file unmodified.
set saveImageName to save in saveImageName as JPEG
--Match the output JPG file date/time to that of the NEF source file.
tell application "Finder" to set modification date of saveImageName to fileTimestamp
end tell
end repeat
end tell
tell application "Finder"
display alert "Done. Duplicated selected NEF files in
" & theOutputFolder & "
as JPGs with dates/times matching NEFs."
end tell
Below was my initial attempt to create an AppleScript to spare me the hours it would take to do this manually with the Preview app on my hundreds of NEF files. It works, but the helpful folks on this website helped me to greatly improve it. As you can see from the initial user prompt, I wanted to prompt the user only in the event that an existing JPG file will be replaced. I also wanted to have the output file names be n.JPG rather than n.NEF.jpg and have the output JPG file inherit the original NEF file's Creation Date & Time. I welcomed any suggestions, though since I'd already come this far my preference was to refrain from adding shell scripts and do it all with AppleScript if possible.
set theImageFolder to choose folder with prompt "Note: This script will replace any existing files in the selected folder matching
the name of a NEF file and end in a JPG extension with a new file of that name.
For example, X.NEF will create X.JPG and replace any existing file named X.JPG
that was already in the selected folder (not in any other folders). To begin now,
Select a folder with NEF images to convert into JPEG images:"
set theOutputFolder to theImageFolder
tell application "Finder"
set theImages to every file of theImageFolder whose name extension is "NEF"
end tell
tell application "Image Events"
launch
repeat with a from 1 to length of theImages
set theImage to file ((item a of theImages) as string)
set theImageReference to open theImage
tell theImageReference
set theImageName to name
save in ((theOutputFolder as string) & theImageName & ".JPG") as JPEG
end tell
end repeat
end tell
tell application "Finder"
display alert "Done. All NEF files in the selected folder have been duplicated in JPEG format."
end tell
Thank you so much, Atomic Toothbrush!
I can't seem to insert a blank line to a Comment or mark as Code here without it saving the Comment, so here's a followup as an Answer. Really it's more of a revised Question. :}
Seems to me it's very close to working as hoped. I replaced the code inside the Repeat section with the fascinating snippet you suggested, though I don't yet fully understand the tricks it's doing. With one file in the target folder the script aborts highlighting the word "alias" with this message:
error "File Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG wasn’t found." number -43 from "Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG"
With two files in the target folder and the "as alias" removed, it creates DSC_2070.JPG just fine but doesn't change the mod date and aborts with this message:
error "Can’t set modification date of \"Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG\" to date \"Wednesday, August 28, 2013 1:03:29 PM\"." number -10006 from modification date of "Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG"
If I run it once to create the JPG file as above, then add the "as alias" back in and run it again it does change the date (for both creation and modification!) to match the source file but then aborts highlighting the last Tell inside the Repeat with this message:
error "File Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG wasn’t found." number -43 from "Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG"
Looks like it's remembering the last file processed because if I rename the file, remove the "as alias" and run it again it aborts highlighting that same last Tell line inside the Repeat with this message referencing the file name that's no longer in the folder:
error "Can’t set modification date of \"Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG\" to date \"Wednesday, August 28, 2013 1:14:19 PM\"." number -10006 from modification date of "Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG"
Complete script with Repeat string inserted as tested above:
set theImageFolder to choose folder with prompt "Select a folder with NEF images to convert into JPEG images:"
set theOutputFolder to theImageFolder
tell application "Finder"
set theImages to every file of theImageFolder whose name extension is "NEF"
end tell
tell application "Image Events"
launch
repeat with a from 1 to length of theImages
set theImage to file ((item a of theImages) as string)
tell application "Finder" to set fileTimestamp to creation date of theImage
set theImageReference to open theImage
tell theImageReference
set theImageName to name
set savedDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"."}
set delimitedList to every text item of theImageName
ignoring case
if last item of delimitedList is "NEF" then
set filenameList to items 1 thru -2 of delimitedList
set theImageName to filenameList as string
end if
end ignoring
set AppleScript's text item delimiters to savedDelimiters
set saveImageName to ((theOutputFolder as string) & theImageName & ".JPG") as alias
save in saveImageName as JPEG
tell application "Finder" to set modification date of saveImageName to fileTimestamp
end tell
end repeat
end tell
tell application "Finder"
display alert "Done. All NEF files in the selected folder have been duplicated in JPEG format with modification date and time changed to match the NEF source file."
end tell
You could also use sips to convert the images and touch -r to change the modification (and creation) times:
for f in *.nef; do jpg="${f%nef}jpg"; sips -s format jpeg -s formatOptions 90 "$f" -o "$jpg"; touch -r "$f" "$jpg"; done
touch -r normally changes only the modification and access times, but it also changes the creation time if the target time is before the original creation time.
If the files have different creation and modification times, you can use SetFile and GetFileInfo:
SetFile -m "$(GetFileInfo -m "$f")" "$jpg"; SetFile -d "$(GetFileInfo -d "$f")" "$jpg"
-m changes the modification time and -d changes the creation time. SetFile and GetFileInfo are part of the command line tools package that can be downloaded from developer.apple.com/downloads or from Xcode's preferences.
From the filename point of view, it sounds like you just need to strip the .NEF extension from the filename. You can do this by turning the filename string into a list, using "." as a delimiter, remove the last item from the list, then reassemble the list to the filename string. I think this should do it (inserted into "repeat" block):
set theImage to file ((item a of theImages) as string)
tell application "Finder" to set fileTimestamp to creation date of theImage
set theImageReference to open theImage
tell theImageReference
set theImageName to name
set savedDelimiters to AppleScript's text item delimiters
-- Split filename string into list, using "." as a delimiter
set AppleScript's text item delimiters to {"."}
set delimitedList to every text item of theImageName
-- Remove the .NEF extension from the list, if it was there
ignoring case
if last item of delimitedList is "NEF" then
set filenameList to items 1 thru -2 of delimitedList
set theImageName to filenameList as string
end if
end ignoring
-- Restore delimiters to default in case of other users
set AppleScript's text item delimiters to savedDelimiters
-- Construct full path of file to save
set saveImageName to ((theOutputFolder as string) & theImageName & ".JPG")
-- Check for file existence
tell application "Finder"
if exists file saveImageName then
-- Check with user - skip to the next file if user doesn't want to overwrite
if button returned of (display dialog saveImageName & " already exists. Overwrite?" buttons {"Yes", "No"}) is "No" then exit repeat
end if
end tell
-- Save the file
set saveImageName to save in saveImageName as JPEG
-- Fiddle the timestamp of the saved file
tell application "Finder" to set modification date of saveImageName to fileTimestamp
end tell
Note I don't think you can easily change t)he creation date on the .JPG file (it is a r/o property in the finder dictionary. The best I can do is set the modification date of the .JPG file to the creation date of the .NEF file.

OSX: How can check whether a file exists in current directory using applescript?

I want to make an automator app which creates an empty file in current directory.
I did some google search and found:
http://hints.macworld.com/article.php?story=20050219134457298 and http://hints.macworld.com/article.php?story=20100509134904820
However, I want to do something more powerful.
If the specified file already exists, I want to show a warning instead of overwriting the original file, which is what one of the above link does. (The other one creates a text file using textEdit. I do not want to create text file. I want an empty file like what linux/unix does)
I already figured out how to do most of the part, but
How can check whether a file exists in current directory using applescript??
How can I concatenate two variable in applescript?
Checking if a file exists (assuming thefullpath is already set as in the referenced question):
tell application "Finder"
if exists POSIX file thefullpath then
--do something here like
display alert "Warning: the file already exists"
end if
end tell
Not sure what you mean by the second part but if you want to concatenate strings stored in var1 and var2 you could simply do
var1 & var2
Something I have been using a lot of late for this sort of thing is the command /bin/test
The test test for the existence of in this case a file
if (do shell script "/bin/test -e " & quoted form of (POSIX path of theFile) & " ; echo $?") is "1" then
-- 1 is false
--do something
end if
The -e option:
-e file True if file exists (regardless of type).
The are tons of other test options shown in the /bin/test man page
The following code, adapted from your second link, is usually right, but it doesn't always work. The current directory is better specified as the directory of the document that is being opened which is most likely from the Finder's front window, but not necessarily. I like to write code that will work no matter what.
on run {input, parameters}
tell application "Finder"
set currentPath to insertion location as text
set x to POSIX path of currentPath
display dialog "currentPath: " & (x as text)
end tell
return x
end run
I wrote a whole "Run AppleScript" action to put things into context:
on run {input, parameters}
# count the number of files
set numFiles to 0
repeat with f in input
# warn the user that folders are not processed in this app
tell application "Finder"
if (kind of f is "Folder") then
display dialog "The item: " & (f as text) & " is a folder. Only files are allowed. Do you want to continue processing files or do you want to cancel?"
else
set numFiles to numFiles + 1
end if
end tell
end repeat
# require that at least one file is being opened
if numFiles < 1 then
display alert "Error: the application Test1.app cannot be run because it requires at least one file as input"
error number -128
end if
# get the current directory from the first file
set theFirstFile to (item 1 of input)
tell application "System Events" to set theFolder to (container of theFirstFile)
# ask the user for a file name
set thefilename to text returned of (display dialog "Create file named:" default answer "filename")
# create the file
tell application "System Events" to set thefullpath to (POSIX path of theFolder) & "/" & thefilename
set theCommand to "touch \"" & thefullpath & "\""
do shell script theCommand
# return the input as the output
return input
end run
The "touch" command is OK. If the file doesn't exist, it is created and if it does exist, only the modification date is changed (which isn't too bad) but it doesn't overwrite the file. If your file is being overwritten, it's not the touch command that is doing it.
I changed the default file name to remove the extension ".txt" This extension may default to being opened by TextEdit.app, but you can change this in the Finder by choosing "Get Info" for a file and changing the "Open With" property. You can change which application opens the file with that extension or you can change them all. For example, all of my ".txt" files are opened with BBEdit.app
Will you vote my answer up?
Another option that doesn't require Finder or System Events is to try to coerce a POSIX file or file object to an alias:
try
POSIX file "/tmp/test" as alias
true
on error
false
end try

Resources