Open Finder alias - applescript

I'm relatively new to Applescript, I was hoping someone can help me resolve this one...
I have a script that does a spotlight search and returns the found items as founditems. The result will either be a folder or an alias to a folder. I'd like to open the found item and it works if the result is a folder but I can't figure how to handle an alias. With an alias I get the error incorporated in the code
try
set theapp to default application of (get info for (POSIX file founditems)) as string
tell application theapp to open (POSIX file founditems as string)
activate application theapp
on error e
display dialog "An error has occured trying to open your file:" & return & return & e buttons {"OK"} default button 1
end try
I get 10665 error code. My guess is that incorporating original path may resolve the alias issue but I'm not sure how to plug it in... Thanks much
founditems is created this way:
set input_var to "12345"
set spotlightquery to "\"kMDItemFinderComment == '" & input_var & "'\""
set thefolders to {POSIX file "/Volumes/RAIDvolume"}
set founditems to {}
repeat with i in thefolders
set thepath to quoted form of POSIX path of i
if exists thepath then
set command to "mdfind -onlyin " & thepath & " " & spotlightquery
set founditems to founditems & (paragraphs of (do shell script command))
end if
end repeat

So it was a list because you used "paragraphs of" and I can see now that founditems is a list of posix paths. As such the following will open it with the default application regardless if the path is to a file, folder or alias.
set founditems to {"/Users/hmcshane/Desktop/aaa alias"}
set macPath to POSIX file (item 1 of founditems)
tell application "Finder" to open macPath

Related

How do I get the properties or the info of a file using AppleScript?

I need to write the properties or at least the info of a file I have only the name of (here: "text2.txt") to a textfile.
I tried various ways but each time I just get the properties of the Desktop folder but not the file.
What am I doing wrong here?
try
tell application "Finder"
set this_folder to path of (folder of the front Finder window) as alias
end tell
on error
-- no open folder windows
set this_folder to path to desktop folder as alias
set is_desktop to true
end try
tell application "System Events"
set file_list to the name of every file of this_folder
end tell
tell application "Finder"
set theFile to path to desktop folder
set myList to {}
repeat with n from 1 to count of file_list
set currentFile to item n of file_list
set the_filePath to this_folder
set the_filename to currentFile
if currentFile contains "text2.txt" then
set {creation date:creaDate, modification date:modDate, name:fName, displayed name:dName, name extension:nExt, description:descript, URL:fPath} to properties of the_filePath
set theText to creaDate & "#" & modDate & "#" & fName & "#" & dName & "#" & nExt & "#" & descript & "#" & fPath
do shell script "echo " & theText & ">> $HOME/Desktop/FileProperties.txt"
end if
end repeat
end tell
I think you mostly have it right already.
Finder windows have a 'target', which is the folder that the window looks at. You can get and set the target normally. Everything below the try statement is unchanged.
try
tell application "Finder" to set this_folder to target of front window as alias
on error
set this_folder to (path to desktop) as alias
set is_desktop to true
end try
As alternatives, the script could use TextEdit or its own 'write' command to create the text document. If you're curious, let me know and I'll add those options.
Okay… here is a script you can try that should handle the writing within applescript. I've made a few other tweaks, all of which are commented (which unfortunately, make the script appear longer than it really is).
Applescript has a built-in 'File Read/Write suite' which you can read about each command in the Language Guide here, but in a nutshell, you use these commands to write to a new file, replace or append text to an existing file.
p.s. I changed some of your variable names
-- Make front window specifier a global var. Unnecessary if you integrate System Events block into Finder block (see below)
global fw
tell application "Finder"
try
set targFol to target of front window as alias
set fw to front window
on error
set targFol to (path to desktop) as alias
set fw to make Finder window to targFol
end try
end tell
The system events block below could also be handled by the Finder. If the folders you're rooting through don't typically have thousands of files in them (or if the alternative line is sufficient), you should consider doing so, as the primary advantage of using System Events is performance with high file counts. I don't think any changes would be required beyond removing the appropriate 'tell/end' statements.
tell application "System Events"
-- Some filtering options as an alternative to the repeat loop
set txFiles1 to files of targFol whose kind is "Plain Text Document"
set txFiles2 to files of targFol whose kind is "Plain Text Document" and name is "text2.txt"
set txFile to item 1 of txFiles2
-- Alternatively, you can just use the file itself, without any of the rigmarole.
set txFile to file "text2.txt" of targFol
end tell
tell application "Finder"
set {creation date:creaDate, modification date:modDate, name:fName, displayed name:dName, name extension:nExt, description:descript, URL:fPath} to properties of targFol
set newText to creaDate & "#" & modDate & "#" & fName & "#" & dName & "#" & nExt & "#" & descript & "#" & fPath as text
end tell
-- Write the properties as text to a text file -- requires the 'class furl' bit to work
set tf to (path to desktop as text) & "FileProperties.txt" as «class furl»
-- Alternatively, you could create the text file in the target folder
-- set tf to (targFol as text) & "FileProperties.txt" as «class furl»
close access (open for access tf)
write newText to tf as text
-- And some obvious things you can do with your new text file
tell application "TextEdit" to open tf
tell application "Finder" to select tf
set rtext to read tf
I made a few adjustments to your code. Maybe something like this will help you out.
property theFile : "text2.txt"
tell application "Finder"
try
-- Gets The Name Of The Front Finder Window If There Is One Opened
set containerName to name of front Finder window as POSIX file as text
-- Checks If The File "text2.txt" Exists In That Folder
-- fileExists Will Be Set To True Or False Depending On The Results
set fileExists to (containerName & theFile) as alias exists
on error errMsg number errNum
-- If Either Of The Previous Commands Throws An Error
-- This Will Give You An Option To Choose A Folder Where You Think
-- The File "text2.txt" Is Located
activate
set containerName to my (choose folder with prompt "Choose A Folder") as text
end try
try
-- Checks If The File "text2.txt" Exists In The New Chosen Folder
set fileExists to (containerName & theFile) as alias exists
on error errMsg number errNum
-- If "text2.txt" Does Not Exist In This Folder Either, Script Stops Here
return
end try
delay 0.1
-- If fileExists Is Set To True From Previous Commands
if fileExists then
set fullFilePath to (containerName & theFile) as alias
set {creation date:creaDate, modification date:modDate, name:fName, displayed name:dName, name extension:nExt, description:descript, URL:fPath} to properties of fullFilePath
set theText to creaDate & "#" & modDate & "#" & fName & "#" & ¬
dName & "#" & nExt & "#" & descript & "#" & fPath
tell current application to (do shell script "echo " & theText & ¬
">> $HOME/Desktop/FileProperties.txt")
end if
end tell

AppleScript: Download URL from file and keep the names

I want to create a simple AppleScript:
define a folder (that will get all the images, docs etc.)
read a file (.txt for example)
download all the URLs into the folder with their original name
Currently, my file has one URL by line, no separator.
I found several scripts but they always do something I don't want, don't need or doesn't work.
I found one that is very close to what I want, but it's editing the names in the loop.
I didn't succeed to split the URL and keep the last part.
Here it is:
property desktopPath : path to desktop as string
set n to 1
repeat with urlLine in paragraphs of (read alias (desktopPath & "filename.txt"))
set qURL to quoted form of urlLine
if qURL ≠ "''" then
set dest to quoted form of ¬
(POSIX path of desktopPath & "URLs/" & n & ".jpg")
do shell script "curl " & quoted form of urlLine & " > " & dest
set n to n + 1
end if
end repeat
If you have any other solution, I take.
Thanks in advance
I found a script that is working fine.
You just need to be sure about the txt file: the list inside should not have any text format.
Weirdly I have to do a copy/paste through a text editor to remove every text format.
1/ Put the txt file on your desktop, 2/ Create a "download" folder on your desktop, 3/ Start the script
set theList to (path to desktop as text) & "Download.txt" -- File name with the URLs
set theFolder to (path to desktop as text) & "download" -- Folder name between quotes
set theFolder to quoted form of POSIX path of theFolder
set theImages to read alias theList as list using delimiter linefeed
repeat with i from 1 to count of theImages
set thisItem to item i of theImages
do shell script "cd " & theFolder & "; " & "curl -O " & quoted form of thisItem
end repeat

how to fix 100's of alias' on mac after migration?

I really hope someone can help me out with this. I recently moved from one mac to another and did a clean install. I have several folders with hundreds of alias (how do you say the plural of alias?)...
The original file path is "/Volumes/Media Drive/Ableton/Warped Tracks/", and the new path needs to be "/users/joel/Music/Ableton Projects/Warped Tracks"
I see how to fix them one at a time, but that would take hours. I tried this applescript, but had no luck:
https://apple.stackexchange.com/questions/2656/how-do-i-fix-failed-aliases
Can anyone give me a better applescript or another solution? As I mentioned, I tried this applescript:
tell application "Finder"
set these_items to the selection
end tell
repeat with i from 1 to the count of these_items
set this_item to (item i of these_items) as alias
set this_info to info for this_item
if class of this_item is alias then
tell application "Finder"
set original_file to original item of this_item
set this_alias_file_name to displayed name of this_item
set container_folder to container of this_item
set the_path to the POSIX path of (original_file as alias)
set new_path to my replaceText("/Volumes/Media Drive/Ableton/Warped Tracks/", "/users/joel/Music/Ableton Projects/Warped Tracks", the_path)
move this_item to trash
try
make new alias file at container_folder to (POSIX file new_path) with properties {name:this_alias_file_name}
on error errMsg number errorNumber
if errorNumber is -10000 then -- new original file not found, try relinking to old
try
make new alias file at container_folder to (POSIX file the_path) with properties {name:this_alias_file_name}
on error errMsg number errorNumber
if errorNumber is -10000 then -- old original not found. link's dead Jim
display dialog "The original file for alias " & this_alias_file_name & " was not found."
else
display dialog "An unknown error occurred: " & errorNumber as text
end if
end try
else
display dialog "An unknown error occurred: " & errorNumber as text
end if
end try
end tell
end if
end repeat
on replaceText(find, replace, subject)
set prevTIDs to text item delimiters of AppleScript
set text item delimiters of AppleScript to find
set subject to text items of subject
set text item delimiters of AppleScript to replace
set subject to "" & subject
set text item delimiters of AppleScript to prevTIDs
return subject
end replaceText
Any help would be greatly appreciated.
Edit: I think the problem with the applescript for me is that I have folders further down the path that all are different, and THOSE each contain the individual alias files. IE:
"/users/joel/Music/Ableton Projects/Warped Tracks/Folder A/file.alias",/users/joel/Music/Ableton Projects/Warped Tracks/Folder B/file2.alias", etc, etc
I had same issue years ago (transfer between 2 media centers), and I made this program : it asks for folder were all broken alias are and then try to find again original path to rebuild them.
the thing is that any applescript instruction about alias gives error when link is broken, so you must use Finder info window to read original path without error when the link is already broken:
(this program assumes that original file name is unique)
-- Select main folder
tell application "Finder" to set Mon_Dossier to ((choose folder with prompt "Select top folder:" without invisibles) as alias) as string
-- repair alias in this folder and all subsequent folders (entire contents)
tell application "Finder" to set Mes_Alias to every file of entire contents of folder Mon_Dossier whose class is alias file
-- loop on each alias of the folder
repeat with Mon_Alias in Mes_Alias
-- found the original file path of Mon_Alias
-- try first with standard alias call
set F_Source to ""
try
tell application "Finder" to set F_Source to original item of Mon_Alias
end try
if F_Source is "" then
-- the link to original file is broken, then use on windows info method
set F_Source to Origine_Alias(Mon_Alias)
set F_Original to Decompose(F_Source)
-- no need to look original file as is, becuase the link is broken (path changed ?)
-- then directly search for the same file without extension
set Cible to ((chemin of F_Original) as string) & ((Nom of F_Original) as string)
tell application "Finder"
if exists file Cible then
-- file is found without extension
-- then delete alias and create new alias with same name and in same folder
set A_Nom to name of Mon_Alias
set A_Dossier to folder of Mon_Alias
delete Mon_Alias
set Nouvel_Alias to make alias to Cible at A_Dossier
set name of Nouvel_Alias to A_Nom
else
SLog("Alias=" & (Mon_Alias as string) & " File not found=" & Cible)
end if
end tell
else
-- the alias link is still valid : nothing to do ! go to next alias..
end if
end repeat
-- end main program
-- sub routine to find passe of broken link (original path/file can't be found)
-- the result is a unix path like folder/sub_folder/file
on Origine_Alias(F_Alias)
set R to ""
tell application "Finder" to open information window of file (F_Alias as text)
tell application "System Events" to tell process "Finder" to set R to value of static text 19 of scroll area 1 of front window
tell application "Finder" to close front window
return R
end Origine_Alias
-- sub routine to extract, from unix file path, the path, the file name and its extension: result is sent back in a record
-- Warning : we can't use "Posix file of" becuase the path and the file are non longer valid ! (then Posix gives error)
on Decompose(Local_F)
--search the first "." from right to find extension
set X to length of Local_F
repeat while (character X of Local_F is not ".") and (X > 0)
set X to X - 1
end repeat
if X > 0 then
set L_Ext to text (X + 1) thru (length of Local_F) of Local_F
set Local_F to text 1 thru (X - 1) of Local_F
else
L_Ext = "" -- "." not found, then no extension !
end if
-- search first "/" from the right to extract file name
set X to length of Local_F
repeat while (character X of Local_F is not "/")
set X to X - 1
end repeat
set L_Nom to text (X + 1) thru (length of Local_F) of Local_F
set Local_F to text 1 thru (X) of Local_F
try
set L_Chemin to POSIX file Local_F
end try
return {chemin:L_Chemin, Nom:L_Nom, Ext:L_Ext}
end Decompose
-- sub routine log (text log file on desktop)
on SLog(msg)
set the my_log to ¬
((path to desktop) as text) & "My_logfile.txt"
try
-- open file. create it if not yet exist
open for access file the my_log with write permission
-- add text at end of file
write (msg & return) to file the my_log starting at eof
close access file the my_log
on error
try
close access file the my_log
end try
end try
end SLog

Play sound with AppleScript using afplay and relative file path

I'm trying to create an AppleScript that uses afplay (as suggested here) to play a random sound file that's located in a directory within the same directory as the script.
folder
-- applescript.scpt
-- sounds
----- sound-x.aiff
I found this comment regarding relative paths to be potentially useful:
(POSIX path of (path to me))
However, I keep receiving errors when I try mashing it up with this approach for randomness...
set theNumber to 3
set theFiles to {}
repeat
set file_path to quoted form of (POSIX path of (path to me))
tell application "Finder" to set aFile to (some file of file_path & "/sounds_dir") as text
if aFile is not in theFiles then
set end of theFiles to aFile
tell application "Finder" to open file aFile
do shell script ("afplay " & file_path & " > /dev/null 2>&1 &")
end if
if (count of theFiles) is equal to theNumber then exit repeat
end repeat
In a script, path to me returns the path to the script file but we need its parent path to add a sub path.
To compose the correct path, we can use the subroutine composeFilePath(fileName).
The main action is in the repeat loop. I also added a delay so it's easier to test. Save the script before using since path to me will return a wrong path when its unsaved.
set LOOPS to 3
set soundFolderName to "sounds_dir"
# ---------------------
# SETUP
# ---------------------
set soundFolderFullPath to my composeFilePath(soundFolderName)
tell application "Finder"
if folder soundFolderFullPath exists then
set soundFolder to (folder soundFolderFullPath)
else
set soundFolder to ""
# Customize action when folder does not exist
beep
log "*** Error: folder " & quoted form of soundFolderFullPath & " missing!"
return
end if
if (count files in soundFolder) is 0 then
# Customize action when folder has no items in it
beep
log "*** Error: No items in " & quoted form of soundFolderFullPath & " !"
return
end if
end tell
# -------------------------------------------
# We have "soundFolder" and it has items in it
# -------------------------------------------
repeat LOOPS times
# PLAY RANDOM FILE
# As ONE LINER:
## do shell script "/usr/bin/afplay " & quoted form of (POSIX path of ((some file of soundFolder) as text)) & " > /dev/null 2>&1 &"
# Step By Step
set aRandomFile to some file of soundFolder
set aRandomFile to POSIX path of (aRandomFile as text)
set shellScript to "/usr/bin/afplay " & quoted form of aRandomFile & " > /dev/null 2>&1 &"
do shell script shellScript
delay 1
end repeat
on composeFilePath(fileName)
if fileName is "" then return ""
set pathToMe to path to me -- this is the full path to this script
-- get the folder this script is in:
set thisScriptsFolder to ""
tell application "Finder"
try
set thisScriptsFolder to (get container of pathToMe) as text
end try
end tell
if thisScriptsFolder is "" then
return ""
end if
return thisScriptsFolder & fileName -- full path
end composeFilePath
You have your paths all messed up. Applescript doesn't use "posix paths" so you can't pass that type of path to applications such as the Finder. Shell scripts do use posix paths and you have to quote them.
In addition for applescript, whenever your path is in string format you must put the word "file" or "folder" in front of the path before you use it so that applescript can understand it's an object to be acted upon otherwise applescript just treats it like a string. Also string paths in applescript should be colon delimited (:) rather than slash delimited (/). Finally applescript paths start with the name of your hard drive such as "Macintosh HD".
You can see you must treat paths in applescript much differently than you do with the shell. Anyway, I didn't test this code but using those basic rules this should work. Good luck.
set theNumber to 3
set theFiles to {}
repeat
set file_path to (path to me) as text
set file_dir to file_path & ":sounds_dir:"
tell application "Finder" to set aFile to (some file of folder file_dir) as text
if aFile is not in theFiles then
set end of theFiles to aFile
tell application "Finder" to open file aFile
do shell script "afplay " & quoted form of POSIX path of aFile & " > /dev/null 2>&1 &"
end if
if (count of theFiles) is equal to theNumber then exit repeat
end repeat

Copy multiple files to a folder in newbie appelscript

I'm trying to make an Applescript that takes a list of names and makes a set of folders from it. And then copies files from a choosen folder into each of these newly created folders.
I have search for the answer, but didn't understand them. So if you could be so kind to explaine what and why I should change the code, it would be a great learning experience for me.
set destinationFolder to choose folder
set {text returned:textReturned} to display dialog "enter folder names" default answer return & return & return
if textReturned is "" then return
set folderWithFiles to (choose folder with prompt "Where are the files at?")
repeat with aLine in (get paragraphs of textReturned)
if contents of aLine is not "" then
do shell script "/bin/mkdir -p " & quoted form of (POSIX path of dest inationFolder & aLine)
set folderNew to aLine & ":" as alias
set dest to folderNew on destinationFolder -- as alias
tell application "Finder"
duplicate every file of folderWithFiles to dest
end tell
end if
end repeat
Thanks in advance
Updated: posted answer to myself
Got help from StefanK at macscripter.net
Here is the complete code:
set destinationFolder to choose folder
set {text returned:textReturned} to display dialog "enter folder names" default answer return & return & return
if textReturned is "" then return
try
set theFiles to (choose file with prompt "Where are the files at?" with multiple selections allowed)
end try
repeat with aLine in (get paragraphs of textReturned)
if contents of aLine is not "" then
set newFolder to (destinationFolder as text) & aLine
do shell script "/bin/mkdir -p " & quoted form of POSIX path of newFolder
try
tell application "Finder" to duplicate theFiles to folder newFolder
end try
end if
end repeat

Resources