I am trying to move a file with AppleScript. This Is the code I use:
on adding folder items to this_folder after receiving these_items
repeat with i from 1 to number of items in these_items
set this_item to item i of these_items
set the item_info to info for this_item
set the item_path to the quoted form of the POSIX path of this_item
...
... //irrelevant code here
...
tell application "Finder"
move POSIX file item_path to POSIX file "/Users/mainuser/Desktop/Books"
end tell
end repeat
end adding folder items to
If I replace item_path with a regular path such as /Users/mainuser/Desktop/Test/test.png than it works great. What could be the reason for my problem?
these_items is an array of alias specifiers, any further coercion is not needed
tell application "Finder"
move this_item to folder "Books" of desktop
end tell
the property desktop points always to the desktop of the current user.
By the way: The Finder doesn't accept POSIX paths (slash separated), only the native HFS paths (colon separated).
PS: The reason why item_path does not work is the quotation.
It's only needed in do shell script
Use:
on adding folder items to this_folder after receiving these_items
tell application "Finder" to move these_items to folder "Books" of desktop
end adding folder items to
The after receiving parameter is a list of AppleScript alias values, which is something Finder's move command already understands and knows how to work with. While it's unusual for application commands like move to accept values that aren't references to application objects, it's not completely unknown; particularly with pre-OS X apps like Finder whose scripting support was completely hand-written, allowing developers to make it work in ways that would be helpful to users and not just in ways dictated by dumb, standardized frameworks like OS X's Cocoa Scripting.
Related
I would like to create an Applescript that mimics the behavior of an alias to a specific folder X. If files are dragged to it, they should be moved to folder X, but if the Applescript is just double-clicked, folder X should be opened.
I am an Applescript novice, but adapting things I've found on the web, I have constructed working pieces: one that moves dragged files to X and one that opens X. I do not know enough to combine them with "if...else" logic, so that if nothing is dragged, the folder is opened; but if things are dragged, they are moved to X but X is not opened.
repeat with a from 1 to length of theDroppedItems
set theCurrentDroppedItem to item a of theDroppedItems
tell application "Finder"
set folderMyFolder to folder "/Users/myname/myfolder"
move theCurrentDroppedItem to folderMyFolder
end tell
end repeat
end open
tell application "Finder" to open "Macintosh HD:Users:myname:myfolder"
When your script contains an open handler, it will be passed items dropped onto the application, while the run handler is the one called when the application is double-clicked. You don't need to do any comparisons, just place the statements to be performed in the appropriate handler, for example:
property targetFolder : ((path to home folder) as text) & "path:to:myfolder"
on run
tell application "Finder" to open folder targetFolder
end run
on open droppedItems
repeat with anItem in droppedItems
tell application "Finder" to move anItem to folder targetFolder
end repeat
end open
Note that the Finder doesn't know about POSIX paths, so to use them you will need to coerce the paths to something the Finder can handle, or use something that does know POSIX paths, such as System Events.
I have an Applescript app that can receive files or folders dropped onto its icon:
on open theDroppedItems
tell application "Finder"
set droppedItemSourcePath to (the POSIX path of theDroppedItems)
...
At this point of the script, when my app receives a file or a folder, an unknown and useless Applescript application named "Droplet" displays an open file/folder dialog.
My script was compiled as application with Script Debugger 6.
I don't understand why this strange "Droplet" app asks me something.
The mistake is that theDroppedItems is a list of alias specifiers even if only one file was dropped and getting the POSIX path of a list throws an error
To get all POSIX paths of the dropped items use
on open theDroppedItems
set {TID, text item delimiters} to {text item delimiters, return}
set droppedItemsSourcePaths to POSIX path of (theDroppedItems as text)
set text item delimiters to TID
display dialog droppedItemsSourcePaths buttons {"OK"} default button "OK"
...
To process the files one by one use a loop
on open theDroppedItems
repeat with anItem in theDroppedItems
-- do something with anItem
end repeat
...
Use a Finder tell block only if you are going to use Finder terminology.
The mentioned Droplet is your app.
Objective: Move all files and files in folders to destination folder and maintain the file structure [files and named folders]. Important for music files in albums.
Functional: Move all listed files in SmartFolder [named] to destinationFolder with serial / consecutive move operation and maintain the same file structure and copy of dataFiles listed in SmartFolder.
Key: All files were obtained for transfer. Normal CMD + A, CMD + C, CMD + V hangs up the computer and the transfer does not initiate. The AppleScript to move each dataObject to destinationPath is all.
Facts: How to reference objects [files, folders] and their proper reference format and accepted path syntax; path or POSIX, and use of alias. Basic operations. I ran an AppleScript to move filePath to pathDestination, and was otherwise successful, and would be nice to known the formalization syntax for path reference.
tell application "Finder"
move allFiles to destinationFolder
// recursive/repeat code to loop through all listed files and folder
end tell
Reference: Applescript, show all files with tag
[Moving / selecting listed files from 'smartfolder' containers as active windows and displayLists. It was an alt. solution since AppleScript will not reference the SmartFolder as an object, nor will it dynamically call the listProperty of the SmartFolder object unless called by an unknown or un-reference method or command.
Since your main issue, as far as I can tell, seems to be dealing with SmartFolders in AppleScript, which—as you said—cannot be referenced as folder objects, this little snippet might be of help:
set SmartFolder to "/Users/CK/My Smart Folder.savedSearch"
tell application "System Events" to get value of property list file SmartFolder
set {[Scope], Query} to {SearchScopes, RawQuery} of RawQueryDict of result
set AppleScript's text item delimiters to tab
set Command to {"mdfind -onlyin", ¬
quoted form of Scope as text, ¬
quoted form of Query as text} as text
set SearchResults to paragraphs of (do shell script Command)
--> returns a list of posix files
--> e.g. {"/Users/CK/Downloads/This is file one.txt", ...}
This will return a list of POSIX paths to files that match the search criteria.
I would recommend using System Events rather than Finder to deal with large numbers of files. It can also handle posix paths without the need to manually coerce them into aliases or whatever. So, given a posix path, such as the ones returned in the list using the above code snippet, you simply do this:
set myfile to item 1 of SearchResults
tell application "System Events" to move myfile to "/Users/CK/Desktop"
Without knowing more details of what your smart folder contains (since some searches could easily return a folder plus the contents of that folder, which you'd have to bear in mind when getting your AppleScript to recurse through the search results), I can't give you more than that. But, you said your main problems were being unable to handle SmartFolders and not knowing how to reference files/folders.
This works for me using the latest version of Sierra.
Set the value of property moveToNewFolderto the destination folder of your choice
This script creates a "Choose From List" Dialog, allowing you to choose any smart folder which resides on your system. It will then move all of these files and folders in the chosen smart folder, to your set destination folder.
property savedSearches : (path to home folder as string) & "Library" & ":Saved Searches"
property savedSearchesSubFolders : {}
property namesOfSavedSearchesSubFolders : {}
property selectedSearchFolder : ""
property selectedSearchFolderPath : missing value
property moveTheseItems : missing value
property moveToNewFolder : (path to desktop as text) & "untitled folder" -- change this value to your preferred destination folder
tell application "Finder"
activate
delay 0.1 -- may need to adjust delay time value
open savedSearches
delay 0.1 -- may need to adjust delay time value
reveal savedSearches
delay 0.1 -- may need to adjust delay time value
select savedSearches
delay 0.1 -- may need to adjust delay time value
set current view of Finder window 1 to column view
delay 0.1 -- may need to adjust delay time value
tell its Finder window (POSIX path of savedSearches)
delay 0.1 -- may need to adjust delay time value
set savedSearchesSubFolders to items
set namesOfSavedSearchesSubFolders to name of items
-- Allows to choose any smart folder from a list of all smart folders
set selectedSearchFolder to choose from list namesOfSavedSearchesSubFolders ¬
with title ¬
"Smart Search Folders" with prompt ¬
"Choose Your Folder" OK button name ¬
"OK" cancel button name "CANCEL"
set selectedSearchFolder to selectedSearchFolder as text
set selectedSearchFolderPath to savedSearches & ":" & selectedSearchFolder
set selectedSearchFolderPath to selectedSearchFolderPath as string
end tell
delay 0.2 -- may need to adjust delay time value
select selectedSearchFolderPath
tell Finder window 1
set defaultView to current view
set current view to list view
delay 0.1 -- may need to adjust delay time value
set current view to defaultView
delay 0.5 -- may need to adjust delay time value
tell application "System Events"
key code 0 using command down
end tell
end tell
set moveTheseItems to selection
end tell
tell application "Finder"
set resultObject to move moveTheseItems ¬
to moveToNewFolder ¬
with replacing
end tell
I'm trying to automate JPEGmini which is not entirely scriptable - the only way to control it is via the "Open" dialog.
Repeatedly calling it once per image is extremely slow.
Instead I'm trying to to perform a search for .jpg or .jpeg files in the "Open" dialog, so that within that result set I can select the batch of files I want to process and open them in a single pass.
(More detail after the code example)
-- later within the search results list I get, I want to select these
set filesToSelect to {"/Users/me/Desktop/photo.jpg", "/Users/me/Documents/image.jpeg"}
-- the actual app is JPEGmini but the same principle applies to Preview
tell application "Preview"
-- start the app
activate
-- let it boot up
delay 3
-- ensure it still has focus
activate
end tell
tell application "System Events"
tell process "Preview"
-- spawn "Open" window
keystroke "o" using {command down}
delay 1
-- spawn "Go to" window
keystroke "g" using {command down, shift down}
delay 1
-- Go to root of hard drive
keystroke "/"
keystroke return
delay 1
-- Perform search
keystroke "f" using {command down}
delay 1
keystroke ".jpg OR .jpeg"
keystroke return
end tell
end tell
Having done the above, how do I access the list of search results, repeat over each item and get it's absolute file path?
I've tried a few variations but am getting nowhere.
Thanks for your time.
You could simplify this by using cross between the shell command line and applescript.
set jpegSearch to paragraphs of (do shell script "mdfind -onlyin / 'kMDItemContentType == \"public.jpeg\" '")
The mdfind command
consults the central metadata store and returns a list
of files that match the given metadata query. The query can be a string
or a query expression.
AFAIK this is what spotlight uses.
mdfind documents will give you an idea of how this command works. But ths script searches only in "/" and looks for content type attribute that is public.jpeg
The return is text. A list of POSIX Paths of the matching files. This text is like a text document each path on a new line but in effect one item as far as Applescript is concerned.
They need to be broken up in a applescript list. So I do this by asking for the paragraphs of the result.
Also if you want to open a new finder window:
try something like:
tell application "Finder"
activate
set myWindow to make new Finder window to startup disk
end tell
To answer why you are getting your error in trying to get the POSIX paths of the target of the files.
If you look at the properties of one of the files returned in your Search Window.
tell application "Finder" to set fileList to properties of first file of front window
You will see the file properties have a property named original item
If you really want to do it the way you are doing it then one way is to get the original item. Coerce the result into alias form then get the posix path.
tell application "Finder" to set aFile to POSIX path of (original item of first file of front window as alias)
In a normal finder window you can use.
tell application "Finder" to set fileList to POSIX path of (first file of front window as alias)
These are just examples to show you whats going on.
The difference in the type of finder window results is because in a Search window what is being displayed is alias files (class:alias file) to the original files, hence the original item property.
Update 2.
To go through your items in your list and check them against another list is simple.
Apple have some tools that will help you with the code.
When in your script.
crtl + Mouse Click the Variable that will hold the jpg result as a list.
This will give you a contextual menu that contains helper code.
Go to the Repeat routines folder in the menu.
Then to its 'Process Every Item'
This will add a repeat routine to your code.
And from there you can use it to check each item against your other list.
set yourOtherList to {"/Library/Desktop Pictures/Abstract/Abstract 2.jpg", "/Library/Desktop Pictures/Abstract/Abstract 1.jpg"}
set jpegSearch to paragraphs of (do shell script "mdfind -onlyin / 'kMDItemContentType == \"public.jpeg\" '")
repeat with i from 1 to number of items in jpegSearch
set this_item to item i of jpegSearch
if this_item is in yourOtherList then
-- do something
log this_item
end if
end repeat
The repeat routine works like this.
It loops over each item in the given list
It will iterate from item 1 to the count of the items in the list.
The i variable holds the loop iteration number. I.e it will be 1 on the first loop and 300 on the 300th loop.
so on the first loop set this_item to item i of jpegSearch is equivalent to writing set this_item to item 1 of jpegSearch
But apple saves you having to write each number of each item with the Repeat with i..
The variable i can be any word or letter you choose that conforms to the normal allowed Variable naming syntax.
Something you can do is build a new list from the matched items. by copying them into a previously declared list. You can then work on that list after the repeat loop has completed.
Here bigList is declared as a empty list {}
The matched items are copied to the bigList. Each new item it receives is added to the end of the list.
set bigList to {}
set yourOtherList to {"/Library/Desktop Pictures/Abstract/Abstract 2.jpg", "/Library/Desktop Pictures/Abstract/Abstract 1.jpg"}
set jpegSearch to paragraphs of (do shell script "mdfind -onlyin / 'kMDItemContentType == \"public.jpeg\" '")
repeat with i from 1 to number of items in jpegSearch
set this_item to item i of jpegSearch
if this_item is in yourOtherList then
copy this_item to end of bigList
end if
end repeat
bigList
I want AppleScript to loop through a set of of RTF files in folder and save them as HTML files.
This is my simple code so far. The XXXX is where I'm struggling:
tell application "Finder"
set source_folder to choose folder
set aList to every file in source_folder
repeat with i from 1 to number of items in aList
tell application "TextEdit"
set aFile to (item i of aList)
save as aFile XXXXXXXXX
end tell
end repeat
end tell
I'm really new to this... any help much appreciated.
You don't need TextEdit for this. There is a command line program textutil which will do the job without all the opening and saving stuff required with TextEdit. We can fix your TextEdit script (it has a few errors) but try this first and let us know if it does the job for you. The html files will have the same name but with the html extension and will be located in source_folder. The ouput path can be changed in the code by using the "-output" switch of textutil. See "man textutil" if you want to look at everything it can do.
And a general question... what is a RTD file? Do you mean rtf or rtfd? Textutil will work with rtf/rtfd but not rtd, so I hope that isn't really your file type.
set source_folder to choose folder with prompt "Choose a source folder."
set output_folder to choose folder with prompt "Choose an output folder."
tell application "Finder"
set theFiles to (files of entire contents of source_folder) as alias list
end tell
repeat with aFile in theFiles
tell application "Finder"
set fileName to name of aFile
set fileExt to name extension of aFile
end tell
set outputPath to (output_folder as text) & text 1 thru -((count of fileExt) + 1) of fileName & "html"
do shell script "/usr/bin/textutil -convert html -output " & quoted form of POSIX path of outputPath & space & quoted form of POSIX path of aFile
end repeat
You mention you are new to applescript, so I'll give you some general pointers you should keep in mind when writing applescript code.
Avoid putting tell blocks of code inside each other. You have tell app TextEdit inside tell app Finder. That's bad. Doing this is a source of many conflicts because you are basically telling the Finder to tell TextEdit to do something. That's not good because commands can get confused and it's really hard to debug these kinds of issues. So keep your tell blocks separate.
Avoid telling an application to perform a command that is not in its applescript dictionary. You should only tell an application to do commands that it knows and an application only knows about the commands in its dictionary. So for example, you are telling the Finder to "choose folder". The Finder does not know that command. That's an applescript command. So doing as you have done is another possible source of errors. In this case that's a simple command and it will work but in general avoid doing this.
Regarding the Finder, you should avoid using it too much. The Finder is a major program on your computer and is often busy doing computer related stuff. As such it's best to only use it when necessary. As an example you can see in my code that I removed the "choose folder" and the repeat loop from the Finder. I purposely appended "as alias list" to the end of the Finder command to make the list of files usable outside of the Finder tell block of code. Of course use the Finder if needed but it's best to not use it if you don't need it.
Use the applescript dictionary of your applications. As mentioned above, the dictionary lists all of the terms and the syntax that an application understands (granted the dictionaries are difficult to understand but you will get better at it the more you use them). Under the file menu of AppleScript Editor choose "Open dictionary" and a list of all the applications that understand applescript is shown. Choose an application from that to see its dictionary. So for example, you are trying to figure out TextEdit's "save as" command. You can usually get good direction from the dictionary so you should take a look at that. Use the search field to search!
So I hope that helps! Good luck.