Applescript Choose file, filename - macos

What I'm trying to make is something like this:
set filename to (choose file)
display dialog "The name of the chosen file is: " & filename
But when I use that script it will return a path to the file something like .../.../.../.../nameoffile.jar. But what I want is that it will return the filename and not the path (so just only nameoffile.jar). Is there a way to do that?
Thanks for reading, please give an answer as soon as possible ;),
Jort

Use the Finder Suite:
set chosenfile to (choose file)
tell application "Finder"
display dialog "The name of the chosen file is: " & (name of chosenfile)
end tell

Related

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 help naming .plist and removing extention

i am creating an applescript to create a file with property list elements but without the .plist extension!
my issue is if i use a dialog to get the name of the file eg.
tell application "SystemUIServer"
display dialog "Enter filename :- " buttons {"Generate file"} default answer "Generate Keyfile"
set fileName to text returned of result
and create the file on the desktop like so
set text_file to (path to desktop)'s POSIX path & "" & quoted form of fileName & ".NEWextention"
finally i add elements to the .plist
tell application "System Events"
tell (make new property list file with properties {name:text_file})
make new property list item at end with properties {kind:string, name:"regName", value:"FOO"}
make new property list item at end with properties {kind:string, name:"regNumber", value:"BAR" as text}
end tell
end tell
end tell
however the file that is created is has '' when quoted from fileName and still has the .plist extention.
eg input :- myfile
output:- 'myfile'.NEWextention.plist
when i want
myfile.NEWextention
how can i achieve this in applescript?
any help would be greatly appreciated!
many thanks in advance.
below is the fixed code thanks to #McUsr
without his help i would have been at the same point for over 6 months of trial and error
tell application "SystemUIServer"
display dialog "Enter FileName :- " buttons {"Generate file"} default answer "Generate file"
set FileName to text returned of result
set text_file to (path to desktop folder as text) & FileName & ".plist"
set dateStamp to do shell script "date"
tell application "System Events"
tell (make new property list file with properties {name:text_file})
make new property list item at end with properties {kind:string, name:"Name", value:FileName}
make new property list item at end with properties {kind:string, name:"Date", value:dateStamp}
end tell
end tell
end tell
tell application "Finder"
set name extension of file text_file to "newExt"
end tell
You can make it happen afterwards you are done processing it with System Events, by Finder, (set name extension of file "Hfs:path:to:file:with:name.ext" to "new-ext").
But I am not sure if you can expect System Events to regard the file as a property list file, containing property list items afterwards. It is still worth a try though. :)
This is how you must change the name extension, as this don't work with System Events (name extension is a read only property).
tell application "Finder"
set mf to (path to desktop folder as text) & "labels.txt"
set name extension of file mf to "text"
end tell
Use the HFS path of the file, aka: Macintosh Hd:Users:You:path:file.ext, and not the posix path. And don't use quoted form of det path.

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

Updating script to find a new type of file

I need to update the script shown below to find a new file type and naming system and have no idea what I'm doing. It use to pull a file named DQXXXXX1.eps and placed in the listed location. The new files are XXXXX_random.pdf. The random in the file name is several series of numbers that change for each file. The important numbers are the first 5, I would like the script to pull all files in that initial location and place into the other location.
The current script is:
set DQfolder to alias "Prepress:ArtFiles:00-Logos A to Z:1-DQ:"
tell application "Finder"
display dialog "enter number" default answer ""
set theNum to text returned of result as string
--try
move alias (DQfolder & "DQ" & theNum & ".eps" as string) to "Macintosh HD:__DQ Incoming:" with replacing
--on error {}
--move alias (DQfolder & "DQ" & theNum & ".tif") to "Macintosh HD:__DQ Incoming:" with replacing
--end try
end tell
Try your script like the following. You have a few things that need to be fixed...
Basically you are adding the strings wrong. You need to first coerce DQfolder to a string before you can add the other strings to it. The way you are doing it can't work because DQfolder is an alias so you can't add other strings to it until you coerce the alias to a string.
the folder path in your command has to be an alias-type file or a folder specification. As such you need to put the word "alias" or "folder" in front of it. A string path will not work. Applescript rarely works with string paths.
"display dialog" is not a Finder command and as such you don't need to put it in the Finder block of code.
"text returned" from your display dialog command is already "text" so you do not need to coerce it to a string. That's why it's called "text" returned... even if you entered a number it's class is still text.
Of course I can't check this code because I don't have files at those paths, but it should work. Good luck...
set DQfolder to alias "Prepress:ArtFiles:00-Logos A to Z:1-DQ:"
display dialog "enter number" default answer ""
set theNum to text returned of result
tell application "Finder"
move alias ((DQfolder as text) & "DQ" & theNum & ".eps") to alias "Macintosh HD:__DQ Incoming:" with replacing
end tell

Getting the file name of files dropped on the script

I made this Applescript script to create symbolic links.
Appart from POSIX path of, how can I get the file name, without the path, of the dropped file?
on open filelist
repeat with i in filelist
do shell script "ln -s " & POSIX path of i & " /Users/me/Desktop/symlink"
end repeat
end open
PS: I know this expects many files to be dropped and tries to create many links with the same name, which gives an error. Actually I copied this example from a website and as I don't know almost anything about Applescript, I don't know how to do this for a single file, help on that would be appreciated too.
I'm not sure what precisely you're trying to do, but I have a guess. Is the idea that you want to take every file dropped on the script and create a symbolic link to each one on the Desktop? So if I drop ~/look/at/me and ~/an/example, you'll have ~/Desktop/me and ~/Desktop/example? If that's what you want, then you're in luck: ln -s <file1> <file2> ... <directory> does exactly that. (Edit: Although you have to watch out for the two-argument case.) Thus, your code could look like this:
-- EDITED: Added the conditional setting of `dest` to prevent errors in the
-- two-arguments-to-ln case (see my comment).
on quoted(f)
return quoted form of POSIX path of f
end quoted
on open filelist
if filelist is {} then return
set dest to missing value
if (count of filelist) is 1 then
tell application "System Events" to set n to the name of item 1 of filelist
set dest to (path to desktop as string) & n
else
set dest to path to desktop
end if
set cmd to "ln -s"
repeat with f in filelist & dest
set cmd to cmd & " " & quoted(f)
end repeat
do shell script cmd
end open
Note the use of quoted form of; it wraps its argument in single quotes so executing in in the shell won't do anything funny.
If you want to get at the name of the file for another reason, you don't need to call out to the Finder; you can use System Events instead:
tell application "System Events" to get name of myAlias
will return the name of the file stored in myAlias.
Edit: If you want to do something to a single file, it's pretty easy. Instead of using repeat to iterate over every file, just perform the same action on the first file, accessed by item 1 of theList. So in this case, you might want something like this:
-- EDITED: Fixed the "linking a directory" case (see my comment).
on quoted(f)
return quoted form of POSIX path of f
end quoted
on open filelist
if filelist is {} then return
set f to item 1 of filelist
tell application "System Events" to set n to the name of f
do shell script "ln -s " & ¬
quoted(f) & " " & quoted((path to desktop as string) & n)
end open
It's pretty much the same, but we grab the first item in filelist and ignore the rest. Additionally, at the end, we display a dialog containing the name of the symlink, so the user knows what just happened.
As an example, you can work with the Finder instead of a shell script to get the name of a single file that is dropped on the script that is saved as an application. If you don't need the display dialog, you can remove it, but you have the file name as a variable to work with:
on open the_files
repeat with i from 1 to the count of the_files
tell application "Finder"
set myFileName to name of (item i of the_files)
end tell
display dialog "The file's name is " & myFileName
end repeat
end open

Resources