Applesricpt how to move files to /Library/Caches - macos

I am working on a applesript code that allows users to customize the background of there login/change user screen. I am using basic applescript ui at the moment but hope to implement more advanced applescript-objC UI if this is a sucsess. At the moment i am having trouble moving the image "ch_pic" to /library/Caches can you please help me with this problem.
set ch_pic to (choose file)
--Creates variables for paths
--Creates application folder in user library for storing assets and code
tell application "Finder"
move file ch_pic to Library / Caches
end tell
--Moves user selected file to application folder
set the name of file ch_pic to "com.apple.desktop.admin.png"
If you ask i will put your name in the code of the finished product.

Pretty simple if you're just selecting, moving, and renaming a file. Just need to make sure that you're speaking the PATH style that Applescript understands.
Here is an example of the code:
-- Set ch_pic to chosen file (restricting to only recognized "image" types)
set ch_pic to (choose file of type "public.image"))
tell application "Finder"
-- Set cache_folder to Caches destination (~/Library/Caches) as Applescript path (<hard drive name>:Users:<user name>:Library:Caches)
set cache_folder to (((path to library folder from user domain as text) & "Caches"))
-- Copy the file over
copy file ch_pic to folder cache_folder
-- Grab the full Applescript path of the newly placed file (two steps for clarity. 1: set the path. 2: explicitly inform Applescript that this is a file)
set new_pic to ((cache_folder as text) & ":" & name of ch_pic)
set pos_new_pic to (file new_pic)
-- Perform the rename
set the name of pos_new_pic to "com.apple.desktop.admin.png"
end tell

Related

Automatically move files of a certain type from folder A to B whenever they are added to folder A on macOS

Using Automator, I created a "Folder Action" to move files of certain types (i.e. "Kind IS Movie") from folder "FolderA" to folder "FolderB" as soon as they are added to folder "FolderA". It works fine except that it doesn't move files from subfolders (e.g. doesn't work if the movie files are added to "FolderA/SubA/"), and apparently there's no option on Automator to make it work on the subfolders.
Does anyone have any idea about how to either change that on Automator or how could I create a script for that? Thanks!
This following AppleScript folder action code should give you a general idea of how to accomplish what you are looking for. When a file or folder is added to a folder that this folder action is attached to, it will search all folders and sub folders for files (I used QuickTime movie as the kind of file... But you can change that to whatever you want) then those files will be moved to the folder that you will define in property moveToFolder
You can save this following code in Script Editor.app directly into your /Users/Your_User_Name/Library/Workflows/Applications/Folder Actions folder, as a .scpt file. Once the script is saved into that folder, it will be available to attach to any folder as a folder action using the Folder Actions Setup.
-- Set This To The Folder You Want Your Videos Moved To
property moveToFolder : (path to desktop as text) & "moved_videos"
-- Set This To The Kind Of File To Act Upon
property fileKind : "QuickTime movie"
on adding folder items to theFolder after receiving theNewItems
tell application "Finder"
set movieFilesRef to a reference to (files of entire contents of folder theFolder ¬
whose kind is fileKind)
move movieFilesRef to alias moveToFolder
end tell
end adding folder items to
OR Here Is A Version Which Defines The Name Extensions Of The Files To Act Upon
-- Set This To The Folder You Want Your Videos Moved To
property moveToFolder : (path to desktop as text) & "moved_videos"
-- Set This To The Name Extensions Of Files To Act Upon
property videoFileExtensions : {"m4v", "mkv", "avi", "mp4", "mov", "wmv", "mpg"}
on adding folder items to theFolder after receiving theNewItems
tell application "Finder"
set movieFilesRef to a reference to (files of entire contents of folder theFolder ¬
whose name extension is in videoFileExtensions)
move movieFilesRef to alias moveToFolder
end tell
end adding folder items to

How to fix a ~10006 error in applescript when duplicating a file to another folder?

When trying to duplicate files to another folder, the script throws a ~10006 error. This only occurs on some Mac mini computers and works fine on others. I have no idea why it is working on some computers but not on others.
This is the error shown:
Can't set "Macintosh HD:Users:username:Documents:" to <> "Macintosh HD:Users:username:Downloads:new test:portal resources" of application "Finder". (~10006)
tell application "Finder"
set folderToBeMoved to (container of (path to me) as text) &
"portal_resources"
set destinationFolder to path to documents folder as text
set moveFolder to duplicate folder folderToBeMoved to destinationFolder with replacing
end tell
expected output is duplicating file to documents folder. But, when testing on certain Macs, the script shows an error ~10006. It works on other macs perfectly well.
You are going to copy the folder to a literal string (path) which can fail on machines running older system versions.
Remove the as text parameter to get an alias specifier
set destinationFolder to path to documents folder
Try this code:
tell application "Finder"
set folderToBeMoved to folder "portal_resources" of container of (path to me)
set destinationFolder to path to documents folder
set moveFolder to duplicate folderToBeMoved to destinationFolder with replacing
end tell
There were two issues here that I've changed. First, you convert things to text strings and try to modify the strings, but the Finder has a rich language for talking about file objects. You should just leave everything in object form. For instance, this:
folder "portal_resources" of container of (path to me)
tells the finder to find the folder of that name in that container and return an object specifier that you can use directly.
Second, once you have this object, you can't add the 'folder' specifier to it. Where you say:
duplicate folder folderToBeMoved
folderToBeMoved is already an object specifier (an object of the form 'folder [path]') so you're actually asking the Finder for 'folder folder [path],' which throws the error you're seeing. It's like saying to someone "pass the 'pass the salt.'" People are probably smart enough to figure that out; the Finder isn't.

AppleScript : How to get files in folder without hidden files?

I actually have two questions.
How to exclude hidden files like .DS_STORE, Icon when I try to get files in folder ?
I've tried "without invisibles" but it seems not working.
How to set my var the_new_folder as an existing folder if already exists ?
Thanks for answers.
My code:
--
-- Get all files in a selected folder
-- For each file, create a folder with the same name and put the file in
--
tell application "Finder"
set the_path to choose folder with prompt "Choose your folder..."
my file_to_folder(the_path)
end tell
on file_to_folder(the_folder)
tell application "Finder"
-- HELP NEEDED HERE
-- HOW TO EXCLUDE HIDDEN FILES (Like Icon, .DS_STORE, etc)
set the_files to files of the_folder
repeat with the_file in the_files
-- Exclude folder in selection
if kind of the_file is not "Folder" then
set the_path to container of the_file
set the_file_ext to name extension of the_file
-- Remove extension of the file name
set the_file_name to name of the_file as string
set the_file_name to text 1 thru ((offset of the_file_ext in (the_file_name)) - 2) of the_file_name
-- Make the new folder with the file name
try
set the_new_folder to make new folder at the_path with properties {name:the_file_name}
on error
-- HELP NEEDED HERE
-- HOW TO SET the_new_folder AS THE EXISTING FOLDER
end try
-- Move the file in the new folder
move the_file to the_new_folder
end if
end repeat
end tell
end file_to_folder
tell application "Finder"
(display dialog ("It's done!") buttons {"Perfect!"})
end tell
Using the System Events context instead of Finder:
bypasses the problem with the AppleShowAllFiles preference[1]
is much faster in general.
Using the visible property of file / folder objects in the System Events context allows you to predictably determine either all items, including hidden ones (by default), or only the visible ones (with whose visible is true):
# Sample input path.
set the_path to POSIX path of (path to home folder)
tell application "System Events"
set allVisibleFiles to files of folder the_path whose visible is true
end tell
Simply omit whose visible is true to include hidden files too.
The code for either referencing a preexisting folder or creating it on demand is essentially the same as in the Finder context:
# Sample input path.
set the_path to POSIX path of (path to home folder)
# Sample subfolder name
set the_subfolder_name to "subfolder"
tell application "System Events"
if folder (the_path & the_subfolder_name) exists then
set subfolder to folder (the_path & the_subfolder_name)
else
set subfolder to make new folder at folder the_path ¬
with properties {name: the_subfolder_name}
end if
end tell
[1] In order to predictably exclude hidden items, a Finder-based solution is not only cumbersome but has massive side effects:
You need to determine the current state of the the AppleShowAllFiles preference (defaults read com.apple.Finder AppleShowAllFiles),
then turn it off.
then kill Finder to make the change take effect (it restarts automatically) - this will be visually disruptive
then, after your code has run, restore it to its previous value.
then kill Finder again so that the restored value takes effect again.
I believe that your first question is not a problem. Your code works fine for me.
As for the second issue, the simplest method is to use the text representation of the_path, and simply build the new folder, and see if it already exists:
set the_path_Text to (the_path as text)
set try_Path to the_path_Text & the_file_name
if (folder try_Path) exists then
set the_new_folder to (folder try_Path)
else
set the_new_folder to make new folder at the_path with properties {name:the_file_name}
end if
If you are truly having difficulty with the first code section, please post a new question with more details, such as a copy of the Result section of the Script.
Thank you to all of you ! #mklement0 #craig-smith
You will find below the corrected code with your help!
If I share this code, you want to be cited for thanks?
--
-- Get all files in a selected folder
-- For each file, create a folder with the same name and put the file in
--
-- Get user folder
set the_path to choose folder with prompt "Choose your folder..."
my file_to_folder(the_path)
on file_to_folder(the_folder)
tell application "System Events"
-- Get all files without hidden
set the_files to files of the_folder whose visible is true
repeat with the_file in the_files
-- Remove extension of the file name
set the_file_ext to name extension of the_file
set the_file_name to name of the_file as string
set the_file_name to text 1 thru ((offset of the_file_ext in (the_file_name)) - 2) of the_file_name
-- Make a new folder or get the existing
set the_path to POSIX path of the_folder
if folder (the_path & the_file_name) exists then
set the_new_folder to folder (the_path & the_file_name)
else
set the_new_folder to make new folder at folder the_path with properties {name:the_file_name}
end if
-- Move the file to the new folder
move the_file to the_new_folder
end repeat
end tell
end file_to_folder
-- Ending dialog
display dialog ("It's done!") buttons {"Perfect!"}

Applescript: Copy all contents of a folder into every folder in a directory

I'm in a bit of a bind and an Applescript noob. I've been stumbling through a script that would allow me to copy the contents of (TemplateFolder) into all of the client folders in a directory, with the added crux that all of the existing clients' folder contents be moved into a folder within the client labeled "Old Files" or something of the sort. I'll include images with my script thus far to illustrate what I'm trying to achieve. Thank you everyone in advance for all your help.
P.S. Since I don't have the rep required, I'll have to post links to my images.
http://imgur.com/a/lL9q7
The first image is the template folder (the folder I'd like all contents copied into each client folder).
The second image is an example of an existing client folder with all the bad structure (or lack thereof).
The final image is the expected results where the template folder's contents are moved into the client folder and the original content of the client's folder are moved into a separate folder titled "Old Structure Files".
Below is the applescript I've written, with help from others, to copy the contents. However there are missing components and some elements that need to change; currently the applescript simply copies the entire folder rather than just the contents and it makes a simple copy rather than inserting, the script is not recursive for an entire directory, and there's no function to move the existing client files into a "Old Structure Files" folder. Again, any and all help is greatly appreciated :)
on run
set source_folder to choose folder with prompt "Select folder to be duplicated:" as string
my do_main_script(source_folder)
end run
on open of source_folder_list
repeat with i from 1 to number of items in the source_folder_list
set this_folder_path to item i of the source_folder_list as string
if last character of this_folder_path is ":" then
my do_main_script(this_folder_path)
end if
end repeat
end open
on do_main_script(source_folder)
tell application "Finder" to set source_folder to folder (source_folder)
tell application "Finder" to set the target_folder to (parent of source_folder)
if source_folder is not "" and target_folder is not "" then
set new_folder_name to (name of source_folder as string) & " duplicate"
set source_folder to source_folder as string
set target_folder to target_folder as string
my create_new_folder(target_folder, new_folder_name)
my duplicate_folder_structure(source_folder, target_folder & new_folder_name & ":")
end if
end do_main_script
In the script bellow, the template folder is at fixed place on desktop, all the content of the customer selected folder is moved to a new folder "old structure", and after that, all content of the template folder is duplicated into the customer folder. If I well understand, this is what you're looking for :
set Templatefolder to "HD:Users:my_user:Desktop:Template"
set CustomerFolder to (choose folder with prompt "Select customer folder to be re-organised")
tell application "Finder"
set CustomerData to every item of CustomerFolder
set OldF to make new folder in CustomerFolder with properties {name:"Old Strutucture Files"}
move CustomerData to OldF
set Newstructure to every item of folder Templatefolder
duplicate Newstructure to CustomerFolder
end tell

Burning files for a video to backup DVD

I'm working on an AppleScript to burn the files for a church sermon to a DVD for backup. A word about our process.
We have a Sony digital camcorder that we use to video the service. I download those files into iMovie, create an iMovie project, and stitch the pieces together. I add an opening title & ending credits and I share it to the Media Browser at two resolutions. After that, I upload the smaller resolution file to our church's website. I then create an iDVD project using the larger resolution file.
I've got templates for the iMovie project with the opening title & the closing credits in it already, and a template for the iDVD project, and another template for printing out DVD labels. I've already written an AppleScript which duplicates these templates for a specific week. That's working fine.
I've got a lot of work done on a second script to create a Burn Folder in my Desktop folder and create folders in it & create aliases / shortcuts to the original files. But, given that it's video we're copying here, I need to make sure that the minimum amount of data required is burned to the disk.
Specifically, the iMovie Events folder for the week's raw video has two folders created by iMovie in it that I don't want to burn to the DVD. One is a cache & the other has thumbnails. These should be recreated if I have to restore the backup for any reason when I open iMovie.
So I only want to copy the files in the event folder that are not these two folders. The folders are called iMovie Movie Cacheand iMovie Thumbnails.
How do I exclude these two files? The code I've got follows.
-- Script to copy the iMovie project, the iDVD project, and the DVD Label
-- files for a particular week's sermon into a burn folder and then burn it.
property iMovieEvents : alias ((path to movies folder as text) & "iMovie Events.localized:")
property iMovieProjects : alias ((path to movies folder as text) & "iMovie Projects.localized:")
property iMovieSermonsPath : alias ((iMovieProjects as text) & "Sermons:")
property sermonDocumentsPath : alias ((path to documents folder as text) & "Sermons:")
global burnFolder
global thisSermonsPath
global thisSermonsDvdLabels
global thisSermonsdvdproj
global thisSermonsiMovieEvents
global thisSermonsiMovieProject
global sermonCode
to copySermonFiles()
-- Start a conversation with the Finder
tell application "Finder"
-- Create a folder in the burn folder for the iMovie Events
set theFolder to my createFolder(burnFolder, "iMovie Events.localized")
-- Give this operation 5 mintues to complete
with timeout of (5 * 60) seconds
-- Copy the Sermon's iMovie Events folder to the Burn Folder.
-- Need to exclude the iMovie Movie Cache & iMovie Thumbnails folders here
make new alias at theFolder to folder thisSermonsiMovieEvents
end timeout
-- Create a folder in the burn folder for the Sermon's iMovie Project.
set theFolder to my createFolder(burnFolder, "iMovie Projects.localized")
with timeout of (5 * 60) seconds
-- Copy the Sermon's iMovie Project file to the Burn Folder
make new alias at theFolder to file thisSermonsiMovieProject
end timeout
-- Create a folder in the burn folder for the Sermon's documents
set theFolder to my createFolder(burnFolder, "Documents")
-- Create a folder in the burn folder's Documents folder for the sermon
set theFolder to my createFolder(theFolder, sermonCode)
-- Copy the Sermon's iDVD Project and DVD Labels files to the Burn Folder
make new alias at theFolder to thisSermonsDvdLabels
make new alias at theFolder to thisSermonsdvdproj
end tell
end copySermonFiles
-- Helper method that creates a new folder named theName in the dst folder.
to createFolder(dst, theName)
-- Create a string that contains the path to the folder we're going to create
set thePath to (dst as text) & theName
-- Start a conversation with the Finder
tell application "Finder"
-- Does the folder exist already?
if not (exists thePath) then
return make new folder at dst with properties {name:theName}
else
return alias thePath
end if
end tell
end createFolder
to createBurnFolder()
-- Create the name of the Burn Folder
set burnFolderName to sermonCode & ".fpbf"
set desktopPath to (path to desktop) as text
-- Compute the path to the Sermon's folder in the Documents:Sermons folder.
set burnFolderPath to desktopPath & burnFolderName
-- Start a conversation with the Finder
tell application "Finder"
-- Does the burn folder exist?
if not (exists burnFolderPath) then
-- Create the burn folder
set burnFolder to make new folder at desktopPath with properties {name:burnFolderName}
else
set burnFolder to folder burnFolderPath
end if
end tell
end createBurnFolder
to getThisSermonsFiles()
-- Ask the user to pick the Sermon's iMovie Project file.
set thisSermonsiMovieProject to choose file with prompt "Please select the Sermon's iMovie Project:" default location iMovieSermonsPath
-- Extract the sermon code from the Sermon's iMovie Project file name.
set fileext to ".rcproject"
set fileName to (name of (info for thisSermonsiMovieProject))
set sermonCode to text 1 thru ((length of fileName) - (length of fileext)) of fileName
-- Build the path to the Sermon's iMovie Events folder
set thisSermonsiMovieEvents to ((iMovieEvents as text) & sermonCode & ":")
-- Build the path to the Sermon's DVD & DVD Labels files.
set thisSermonsPath to (sermonDocumentsPath as text) & sermonCode & ":"
-- Build the path to this Sermon's DVD Labels file.
set thisSermonsDvdLabels to alias (thisSermonsPath & sermonCode & ".cndx")
-- Build the path to this sermon's iDVD Project file.
set thisSermonsdvdproj to alias (thisSermonsPath & sermonCode & ".dvdproj")
end getThisSermonsFiles
on run
-- Get the sermon code from the user
getThisSermonsFiles()
-- Create the Burn folder
createBurnFolder()
-- Copy the files into the burn folder.
copySermonFiles()
end run
The Finder has a "whose" claus which makes filtering a list of Finder items easy. Thus we can use it to exclude things. You can also refer to files or folders as "items" to include both in one phrase. So if you want to get a reference to all files and folders from a folder, excluding some items by their name, then something like this works...
set itemNamesToExclude to {"iMovie Movie Cache", "iMovie Thumbnails"}
tell application "Finder"
set itemsToMove to items of folder thisSermonsiMovieEvents whose name is not in itemNamesToExclude
-- move itemsToMove somewhere
end tell

Resources