How find the file name of an executing AppleScript - applescript

How do I find the name of an executing AppleScript?
REASON: I want to create a script that changes its behavior based on its filename. Something like:
if myname is "Joe" then ACTION1
else if myname is "Frank" then ACTION2
else ACTION3

The normal way to get the name is by using "name of me". However applescripts are run by applescript runner so when you use that on a script you get "Applescript Runner" as the name. If you compile your script as an application then "name of me" will work. The only way to get the script name is by getting its path and extracting the name. Something like this would thus work for scripts...
getMyName()
tell me to display dialog result
on getMyName()
set myPath to path to me as text
if myPath ends with ":" then
set n to -2
else
set n to -1
end if
set AppleScript's text item delimiters to ":"
set myName to text item n of myPath
if (myName contains ".") then
set AppleScript's text item delimiters to "."
set myName to text 1 thru text item -2 of myName
end if
set AppleScript's text item delimiters to ""
return myName
end getMyName

Here's a method that works for all of the following:
*.scpt files (compiled AppleScript files; run in AppleScript Editor or with osascript)
*.applescript files (uncompiled AppleScript files; run in AppleScript Editor or with osascript)
command-line scripts that directly contain AppleScript (marked as executable and starting with #!/usr/bin/env osascript):
*.app files created with AppleScript Editor
*.app files created with Automator that contain AppleScript actions
Note: By contrast, it does not work for the following:
OS X services created with Automator that contain AppleScript actions (special *.workflow files) - always reports 'WorkflowServiceRunner[.xpc]'
general-purpose *.workflow files created with Automator that contain ApplesScript actions and that are run with automator - always reports 'Automator Runner[.app]'
Get the name of the running script, including filename extension (.scpt, .app, or .applescript, as the case may be):
tell application "System Events" to set myname to get name of (path to me)
If you want to remove the filename extension with a single command, use the following, do shell script-based approach:
tell application "System Events" to set myname to do shell script "rawName=" & quoted form of (get name of (path to me)) & "; printf '%s' \"${rawName%.*}\""
Here's an all-AppleScript alternative that is more verbose (yet concise by AppleScript standards):
tell application "System Events"
set myname to name of (path to me)
set extension to name extension of (path to me)
end tell
if length of extension > 0 then
# Make sure that `text item delimiters` has its default value here.
set myname to items 1 through -(2 + (length of extension)) of myname as text
end if
Finally, here's a variation: a subroutine that you can call with set myname to getMyName():
on getMyName()
local myName, tidSaved
tell application "System Events"
set myAlias to path to me -- alias to the file/bundle of the running script
set myName to name of myAlias -- filename with extension, if any.
if name extension of myAlias is not "" then -- strip away extension
set {tidSaved, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {""}}
set myName to items 1 through -(2 + (length of (get name extension of myAlias))) of myName as text
set AppleScript's text item delimiters to tidSaved
end if
end tell
return myName
end getMyName

An easier way to find out the base part of the path is using name of:
tell application "Finder"
set p to path to me
set nam to name of file p as text
end tell

Maybe this:
set appname to name of current application

Related

AppleScript - array read from disk is empty

I have a script that starts like this:
tell application "Finder"
set theFolder to (choose folder)
set theFile to POSIX path of ((theFolder as string) & "words.txt")
set fileHandle to open for access theFile
set nameArray to paragraphs of (read fileHandle for (get eof fileHandle) as «class utf8»)
close access fileHandle
end tell
File words.txt is there and contains one word per line.
theFile is a valid path to words.txt, something like /Users/myself/Desktop/folder/words.txt.
nameArray comes empty.
Why?
If instead of letting the user choose the folder, I hardcode the path, like
set theFile to "/Users/myself/Desktop/folder/words.txt"
everything works fine.
First of all, you do not need Finder as the necessary commands are just basic AppleScript commands and or are all a part of Standard Additions.
The following three lines, by themselves, will do what you are trying to do:
set theFolder to (choose folder)
set theFile to POSIX path of ((theFolder as string) & "words.txt")
set nameArray to paragraphs of (read theFile as «class utf8»)
Something to keep in mind, if the last line in the file ends with a line feed then the last item in the list will be "" and you can either account for this in your code as you use each item of the list or add the following example to remove it if it exists:
if last item of nameArray is equal to "" then ¬
set nameArray to items 1 thru -2 of nameArray

Checking if an item exists as a folder using POSIX notation in AppleScript

I have a string which represents a File/Folder in a Folder in POSIX notation:
/Users/surfacedetail/Desktop/Temp/Test1
I want to check if the the Test1 exists AND is a Folder. The following tells is that it exists:
if exists my POSIX file myFileOrFolder then
beep
end if
This works ok, but how to tell if it is a Folder or a File?
The problem is that this is part of a massive script, this is a better test, it uses system events, but it doesn't work. I think its something to do with how I am building the path string.
tell application "Finder"
set myScriptFilePath to (path to me)
set mySourceFolder to folder of myScriptFilePath
set myFileAliasList to the entire contents of mySourceFolder
set myPOSIXSourceFolder to URL of mySourceFolder
set myPOSIXSourceFolder to characters 8 thru -1 of myPOSIXSourceFolder as string
repeat with myFile in myFileAliasList
set myFileName to name of myFile
log "myFileName: " & myFileName
if (myFileName ends with ".txt") then
set AppleScript's text item delimiters to "."
set myFolderName to first text item of myFileName
set myFolderPath to myPOSIXSourceFolder & myFolderName as string
log "myFolderPath: " & myFolderPath
tell application "System Events"
if not (exists folder myFolderPath) then
beep
display dialog "Could not find Folder for File: " & myFileName
return {}
end if
end tell
end if
end repeat
end tell
You can do it with System Events without any type cast
set thePath to "/Users/surfacedetail/Desktop/Temp/Test1"
tell application "System Events"
if exists folder thePath then
beep
end if
end tell
Fixed it! It was because I wasn't restoring the text delimiter, it needed this:
set mySaveASDelimiters to AppleScript's text item delimiters
change delimiters
set AppleScript's text item delimiters to mySaveASDelimiters

Combining two (applescript) scripts into one

I'm trying to simplify my workflow by combining the following two applescripts into one, they work fine separately but it'd be more efficient to combine them.
In short, script A trims a file name into the last 3 characters and Script B adds the folder name (where the files reside) to the file name.
This might be a very simple fix but I'm script-writing challenged so any help is welcomed.
SCRIPT A:
on open whichFile
repeat with aFile in whichFile
tell application "Finder"
set filename to name of aFile
set name of aFile to ((characters -1 thru -7 of filename) as string)
--set name of whichFile to ((characters 1 thru -4 of filename) as string) --trim last 3
end tell
end repeat
end open
SCRIPT B
on open theDroppedItems
repeat with a from 1 to length of theDroppedItems
set theCurrentDroppedItem to item a of theDroppedItems
set theCurrentDroppedItem to theCurrentDroppedItem as string
tell application "System Events"
set folderPath to theCurrentDroppedItem as string
--display dialog (folderPath)
set AppleScript's text item delimiters to ":"
set newFileName to (text item -4 of folderPath as string) & "-" & (text item -2 of folderPath as string) & "-" & (text item -1 of folderPath as string)
--display dialog (newFileName)
--rename file
set fileAlias to (theCurrentDroppedItem) as alias
set the name of fileAlias to newFileName
end tell
end repeat
end open
You can start by opening a new Script Editor document for the combined script. The open handler is passed a list of file items, so you can add a new handler declaration with an empty repeat statement that steps through the dropped items. From there, just identify the statements that perform the various operations (trim name, get folder name, etc), and copy them into the new open handler's repeat statement, editing as needed to use consistent variable names.
Once the new script is running, then you can look at optimizing it by combining and/or rearranging statements that may be doing the same thing in the different scripts. It can also be helpful to organize functions into their own handlers, such as the getNamePieces handler below. I also like to add a run handler with a choose file dialog so that you can test without having to drag items onto a droplet.
Note that the file name includes any extension, so you should break it apart in order to work with just the name part. There is also a bit of unnecessary thrashing about in the script that gets the folder name, so after cleaning it up your script could look something like:
on run
open (choose file with multiple selections allowed)
end run
on open droppedItems
repeat with anItem in droppedItems
set {folderPath, theName, extension} to getNamePieces from anItem
set trimmedName to text -1 thru -3 of theName -- work with just the name part
tell application "System Events"
set folderName to name of disk item folderPath
set newName to folderName & "-" & trimmedName & extension -- assemble the pieces
log newName -- for testing
# set name of anItem to newName -- uncomment to go live
end tell
end repeat
end open
to getNamePieces from someItem -- return the containing folder path, the name, and the extension
tell application "System Events" to tell disk item (someItem as text)
set theContainer to path of the container
set {theName, extension} to {name, name extension}
end tell
if extension is not "" then
set theName to text 1 thru -((count extension) + 2) of theName -- just the name part
set extension to "." & extension
end if
return {theContainer, theName, extension}
end getNamePieces

"Can't get last text item of alias" Error When Running AppleScript

I have an AppleScript that runs as part of a Hazel routine monitoring a folder. When the script runs, it picks apart the file targeted by the Hazel routine and then attaches the file to an email and addresses the email with information from the name of the file. Unfortunately, it seems there is an error somewhere in the script, but I cannot seem to locate it.
The only semi-useful information from Console is in the title (i.e., "Can't get last text item of alias"). Here is the script:
on hazelProcessFile(theFile)
set theAttachment1 to (POSIX path of theFile)
set FileName to theFile
--remove trailing slash
set SansSlash to quoted form of text 1 through -2 of FileName
set FileName to SansSlash as text
-- remove path from FileName
set AppleScript's text item delimiters to ":"
set SansPath to last text item of FileName
set FileName to SansPath as text
-- remove extension
set AppleScript's text item delimiters to "."
set SansExtension to every text item of FileName
set last text item of SansExtension to ""
set FileName to SansExtension as text
-- parse using —
set AppleScript's text item delimiters to "—"
set clientName to first text item of FileName
set clientEmail to last text item of FileName
tell application "Airmail 2"
activate
set theMessage to make new outgoing message with properties {subject:"New Invoice from ", content:"Please find attached, infra, the current month's invoice. If you have any questions, please feel free to respond to this email. One-time payments may be made using the following secure form on our website: https://. Thank you for your continued business."}
tell theMessage
set sender to "billing#example.com"
make new to recipient at end of to recipients with properties {name:clientName, address:clientEmail}
make new mail attachment with properties {filename:theAttachment1}
compose
end tell
end tell
end hazelProcessFile
The code is commented, so it should be obvious what each section is supposed to do. I would imagine the issue is in the "remove path from FileName" section, as that is the section that has been giving me the most trouble.
theFile is obviously an alias specifier.
text item and text thru – as the name implies – expects plain text
You have to coerce the alias first to text before dealing with text and remove quoted form of, that's only needed in conjunction with do shell script.
--remove trailing slash
set FileName to theFile as text
set SansSlash to text 1 through -2 of FileName
set FileName to SansSlash
but there is no trailing slash in a HFS path
To strip the file name without extension from an alias this is much easier
tell application "System Events" to set {name:Nm, name extension:Ex} to theFile
set baseName to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
Edit:
Try this optimized code, the Airmail 2 part is skipped and I don't know if the EM Dash character is treated correctly in case you'll copy and paste the code.
on hazelProcessFile(theFile)
set theAttachment1 to (POSIX path of theFile)
tell application "System Events" to set {name:Nm, name extension:Ex} to theFile
set FileName to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
-- parse using —
set {TID, text item delimiters} to {text item delimiters, "—"}
set clientName to text item -2 of FileName
set clientEmail to text item -1 of FileName
set text item delimiters to TID
-- tell application "Airmail 2"
-- ...
end hazelProcessFile

applescript get rid of full path

I've got a choose file in my AppleScript. When I run the script and choose a file, the output is always the full file path with the file extension on the end. For example:
Macintosh HD:Developer:About Xcode.pdf
is what I don't want. I only want:
About Xcode
The below answer by Kassym Dorsel doesn't work when there is more than one . in it.
The below answer by Lri doesn't work with set x to choose file:
error "Can’t make quoted form of alias \"Macintosh HD:Applications:Firefox.app:\" into type Unicode text." number -1700 from quoted form of alias "Macintosh HD:Applications:Firefox.app:" to Unicode text
You can use the Finder to manipulate the names of Finder items:
choose file with prompt "Pick one"
set filepath to result
tell application "Finder" to set {dispName, nameExt, isHidden} to ¬
the {displayed name, name extension, extension hidden} of the filepath
if isHidden or nameExt is equal to "" then
dispName
else
(characters 1 through (-2 - (count of nameExt)) of dispName) as text
end if
set baseName to result
This will work :
set a to "Macintosh HD:Developer:About.Xcode.pdf"
set text item delimiters to ":"
set temp to last text item of a
set text item delimiters to "."
set temp to text items 1 thru -2 of temp as text
Gives => About.Xcode

Resources