I have a question, basically i've wrote "application" in Applescript, and something is quite suspisious.
tell application "Finder"
activate
set theXMLFolder to choose folder with prompt "ok"
set numberOfFiles to count of (files in folder theXMLFolder)
repeat with a from 1 to numberOfFiles
set theXMLFile to item a of theXMLFolder
if name extension of theXMLFile is in validExtensions then
my resetVariables()
my importXMLFolder(theXMLFile as string) -- import and read XML file
my writeToExcel() -- convert XML to Excel file
end if
end repeat
end tell
This is the way how i'm prompting for XML files inside folder. Problem is that when in the folder there are only XML files it works perfect, but in the moment there will be some other files sometimes it doesn't read them all, for ex. it will only find 7 out of 9 files. Is there any way to make it see always and all files?
Thank you
This works for me on the latest version of Sierra
With this code you can bypass the whole “conditional” part of your code
property nameExtension : "xml"
set theXMLFolder to choose folder with prompt "ok"
tell application "Finder"
set theFiles to files of theXMLFolder whose name extension is nameExtension
repeat with i from 1 to number of items in theFiles
set theXMLFile to item i of theFiles
my resetVariables()
my importXMLFolder(theXMLFile as string)
my writeToExcel()
end repeat
end tell
The following example AppleScript code only acts on files having the name extension set in validExtensions, e.g. xml, and will act upon every xml file based on what's in the repeat loop, i.e. -- # Do something.:
set validExtensions to {"xml"}
tell application "Finder"
set theXMLFolder to choose folder with prompt "Select the folder containing the xml files:"
repeat with i from 1 to (count of files in folder theXMLFolder)
set theXMLFile to item i of theXMLFolder
if name extension of theXMLFile is in validExtensions then
-- # Do something.
log (get name of item i of folder theXMLFolder)
end if
end repeat
end tell
Related
I am attempting to create a script or series of scripts to accomplish a semi-complex task. I have already completed the first step, which is to automatically open chrome, visit a site, enter login information and download a .pkg file. What I am looking for is help on making the next part of the script, which is to open the .pkg file from my Downloads folder and install it autonomously. The file name is QuickAdd.pkg, but is renamed as QuickAdd(number).pkg, and hence I need to sort the folder by most recently added. Below is the script that I have so far devised to get the correct file path, but it seems to be very convoluted to me. Any help is greatly appreciated as I am not nearly experienced enough to complete this on my own.
Script v1:
set sourceFolder to (path to downloads folder)
tell application "Finder"
set fileList to (sort (get files of sourceFolder) by creation date)
-- This raises an error if the folder doesn't contain any files
-- Last File is the Most Recently Created --
set theFile to (last item of fileList) as alias
set thePath to POSIX path of theFile
set oProp to (properties of theFile)
set URLstr to URL of oProp
end tell
return URLstr
This works great except that is returns the file path as "file:///Users/wesleycharlap/Downloads/(filename.pkg)", and I cant seem to get any command to recognize the file path as a .pkg and install it. So I assumed the issue was the "file:///" prefix, and thus my second script.
Script v2:
use framework "Foundation"
use scripting additions
set thePath to POSIX path of (path to downloads folder as text)
set sortedList to its filesIn:thePath sortedBy:
(current application's NSURLAddedToDirectoryDateKey)
on filesIn:folderPOSIXPath sortedBy:sortKey
set keysToRequest to {current application's NSURLPathKey, ¬
current application's NSURLIsPackageKey, ¬
current application's NSURLIsDirectoryKey, ¬
sortKey}
set theFolderURL to current application's class "NSURL"'s fileURLWithPath:folderPOSIXPath
set theNSFileManager to current application's NSFileManager's defaultManager()
set listOfNSURLs to (theNSFileManager's contentsOfDirectoryAtURL:theFolderURL ¬
includingPropertiesForKeys:keysToRequest ¬
options:(current application's NSDirectoryEnumerationSkipsHiddenFiles) ¬
|error|:(missing value))
set valuesNSArray to current application's NSMutableArray's array()
repeat with oneNSURL in listOfNSURLs
(valuesNSArray's addObject:(oneNSURL's resourceValuesForKeys:keysToRequest |error|:(missing value)))
end repeat
set theNSPredicate to current application's NSPredicate's predicateWithFormat_("%K == NO OR %K == YES", current application's NSURLIsDirectoryKey, current application's NSURLIsPackageKey)
set valuesNSArray to valuesNSArray's filteredArrayUsingPredicate:theNSPredicate
set theDescriptor to current application's NSSortDescriptor's sortDescriptorWithKey:(sortKey) ascending:true
set theSortedNSArray to valuesNSArray's sortedArrayUsingDescriptors:{theDescriptor}
return (theSortedNSArray's lastObject()'s valueForKey:(current application's NSURLPathKey)) as text
end filesIn:sortedBy:
This version does indeed give me the correct file path "/Users/wesleycharlap/Downloads/(filename).pkg" but I am confused on where to go from here.
Thx for reading
Script v1 can be replaced by
set sourceFolder to (path to downloads folder)
tell application "Finder"
set allFiles to files of sourceFolder whose name extension is "pkg"
if (count allFiles) = 0 then return
set latestFile to last item of (sort allFiles by creation date)
open latestFile
end tell
It considers only .pkg files and opens the most recent one. The next step to automate the install process of the package is not trivial because Installer.app is not scriptable.
I'm working on my first AppleScript and have run into an error on the last command. Basically, the script is supposed to loop through all of the jpg's in a given folder ("/Volumes/Public2/Pictures/LINP/temp/") and move them all into sub-folders based on the date in the file name:
Ex. 000DC5D1A54E(Patio)_1_20130604084734_139988.jpg
Where 20130604 is the date (2013-06-04)
The part of my script that gets each of the file names and loops over them, creating the necessary sub-folders works great. No issues at all. It's when I try the actual "move" that I get a System Events error. So, to start, here's the complete script:
set workFolder to "/Volumes/Public2/Pictures/LINP/temp/"
log workFolder
set workFolder to (POSIX file workFolder) as alias
log workFolder
tell application "System Events"
--get files to work on
set filesToProcess to files of workFolder
--log filesToProcess
repeat with thisFile in filesToProcess
log thisFile
set {fileName, fileExt} to {name, name extension} of thisFile
log fileName
log fileExt
if (fileExt is in "(*jpg*)" and ((length of fileName) is greater than 10)) then
--get name of file without extension
set rootName to text 1 thru -((length of fileExt) + 2) of fileName
log rootName
--break apart the file name to get to the imortant stuff
set AppleScript's text item delimiters to "_"
--store the camera name
set cameraName to text item 1 of rootName
log cameraName
--store the full date
set photoDate to text item 3 of rootName
log photoDate
--cut out the time information
set photoDate to text 1 thru 8 of photoDate
log photoDate
--break out the year
set photoYear to text 1 thru 4 of photoDate
log photoYear
--break out the month
set photoMonth to text 5 thru 6 of photoDate
log photoMonth
--break out the day
set photoDay to text 7 thru 8 of photoDate
log photoDay
--combine parts into a new name of the form "YYYY-MM-DD"
set photoFolder to photoYear & "-" & photoMonth & "-" & photoDay
log photoFolder
--make sure a correctly named folder exists
set targetFolder to my checkForFolder({parentFolder:(workFolder as text), folderName:photoFolder}) as text
log "targetFolder: " & targetFolder
log thisFile
log "targetFolder Class: " & class of targetFolder
log "thisFile Class: " & class of thisFile
set finalTarget1 to (POSIX file targetFolder) as alias as string
log "finalTarget1: " & finalTarget1
log "finalTarget1 Class: " & class of finalTarget1
--Here's where the error pops up. I've tried both HFS and POSIX formats for the target folder, but the issue seems to be with the file
--Yes, the files definitely exist (I've confirmed this). I show exactly what the values are and error messages I'm getting at the end of this post
move thisFile to the folder finalTarget1
move thisFile to the folder targetFolder
end if
end repeat
end tell
to checkForFolder({parentFolder:fParent, folderName:fName})
--find or create a folder
tell application "System Events"
--set fName to POSIX file of fName as alias
--set fParent to POSIX file of fParent as alias
if not (exists POSIX path of (folder fName of folder fParent)) then
set output to POSIX path of (make new folder at end of folder fParent with properties {name:fName})
else
set output to (POSIX path of (folder fName of folder fParent))
end if
end tell
--returns a POSIX path
return output
end checkForFolder
After hours of poring over the Apple Forums, Stack Overflow and consulting the Google oracle, I'm aware that context matters, so I'm trying to provide as much information as possible. Here, I've printed (log) the contents and Class types of thisFile, targetFolder and finalTarget1:
(targetFolder: /Volumes/Public2/Pictures/LINP/temp/2013-06-04)
(targetFolder Class: text)
thisFile
(*file Public2:Pictures:LINP:temp:000DC5D1A54E(Patio)_1_20130604084734_139988.jpg*)
(thisFile Class: file)
(finalTarget1: Public2:Pictures:LINP:temp:2013-06-04:)
(finalTarget1 Class: text)
And here are the errors displayed by each of the two move attempts:
move thisFile to the folder finalTarget1
= move file "Public2:Pictures:LINP:temp:000DC5D1A54E(Patio)_1_20130604084734_139988.jpg" to folder "Public2:Pictures:LINP:temp:2013-06-04:"
error "System Events got an error: Can’t get file \"Public2:Pictures:LINP:temp:000DC5D1A54E(Patio)_1_20130604084734_139988.jpg\". " number -1728 from file "Public2:Pictures:LINP:temp:000DC5D1A54E(Patio)_1_20130604084734_139988.jpg"
move thisFile to the folder targetFolder
= move file "Public2:Pictures:LINP:temp:000DC5D1A54E(Patio)_1_20130604084734_139988.jpg" to folder "/Volumes/Public2/Pictures/LINP/temp/2013-06-04"
error "System Events got an error: Can’t get file \"Public2:Pictures:LINP:temp:000DC5D1A54E(Patio)_1_20130604084734_139988.jpg\". " number -1728 from file "Public2:Pictures:LINP:temp:000DC5D1A54E(Patio)_1_20130604084734_139988.jpg"
Finally, yes, Public2 is mounted and I know that it's accessible since I'm getting the full folder contents back AND creating each of the sub-folders appropriately. It's just this last "move" operation that is failing and I'm sure it's a product of my ignorance.
Can anyone help identify the cause and how I can fix it?
I took your script and quickly made a local version to test, with two jpegs in the temp folder. So far, this is what I came across.
Fix #1:
move thisFile to the folder finalTarget1
needs to be changed to
move thisFile to finalTarget1
but then there's is an error with
move thisFile to the folder targetFolder
because the script is attempting to move the file it already moved. Not sure if that line is in there for testing purposes. Maybe you can clarify. If I comment out the 2nd line it seems to work.
I have the code below to set a variable in Applescript for the path to the iTunes Music Folder:
set username to text returned of (display dialog "RingtoneDude" default answer "Enter your path to your iTunes Ringtones folder here. e.g. /Users/David/Music/iTunes/iTunes Music/Ringtones" buttons {"Confirm", "Cancel"} default button 1)
And then I have the code to call the variable username to copy a file
tell application "Finder"
copy file theCopy to username
end tell
but the file theCopy which is on the desktop (theCopy is a variable) does not move to the folder.
Please help.
I believe you've misunderstood the copy command. The copy command is used for transferring the contents of one variable into another variable. What you need to use is the duplicate command, which is used for copying files to a specified location. Its syntax is as follows:
duplicate [alias] to [alias]
[replacing boolean] --If true, replaces files in the destination with the same name
Having said that, your new code, in conjunction with Uriah Carpenter's answer, should look something like this:
set myRingtoneFolder to choose folder with prompt "Select your iTunes Ringtone folder:"
tell application "Finder" to duplicate theCopy to myRingtoneFolder
I would suggest you use choose folder which returns an alias.
To make some text into an alias object use set myAliasPath to myTextPath as alias.
For more detailed information see Aliases and Files in the AppleScript documentation.
I am trying to batch convert some .doc files to .pdf
I am pretty sure I've got the concept right, I just do not know how to reference the format to change the file format when I "Save As"
set F to choose folder
tell application "Finder"
set P to (files of entire contents of F)
repeat with I from 1 to number of items in P
set this_item to item I of P as alias
tell application "Microsoft Word"
activate
open this_item
save as active document file format format PDF
close window 1
end tell
end repeat
end tell
Thanks
A little google searching would have turned up this...
which is basically the whole script you're trying to write.
I need to create an AppleSript that will copy specified files from one folder to a newly created folder.
These files need to be specified in the AppleScript editor so something like:
start
fileToBeMoved = "Desktop/Test Folder 1/test.doc"
newfoldername = "Test Folder 2"
make newfolder and name it 'newfoldername'
copy 'fileToBeMoved' to 'newfolder'
end
Generally:
tell application "Finder"
make new folder at alias "Macintosh HD:Users:user:Desktop:" with properties {name:"Test Folder 2"}
copy file "Macintosh HD:Users:user:Desktop:Test Folder 1:test.doc" to folder "Macintosh HD:Users:user:Desktop:Test Folder 2"
end tell
You can add variable names that represent POSIX files and paths.
Obviously the colon character (:) is a reserved character for folder- and filenames.
set desktopFolder to "Macintosh HD/Users/user/Desktop/"
set desktopFdrPosix to quoted form of POSIX path of desktopFolder
set newFolderName to "Test Folder 2"
set destinationFdrPosix to quoted form of desktopFdrPosix & POSIX file newFolderName
set sourceFilename to "Test Folder 1/test.doc"
set sourceFnPosix to quoted form of desktopFdrPosix & POSIX file sourceFilename
tell application "Finder"
make new folder at alias desktopFdrPosix with properties {name:newFolderName}
copy file sourceFnPosix to folder destinationFdrPosix
end tell
You may also want to add error checking if the destination folder already exists.
The trick with AppleScript is that moving files is done using aliases.
More realistically it might be easier to make a shell script instead which can be run from AppleScript using do shell script if you're using Automator or something similar.
#!/bin/sh
fileToBeMoved="$HOME/Desktop/Test Folder 1/test.doc"
newFolderName="Test Folder 2"
mkdir "$newFolderName"
cp -a "$fileToBeMoved" "$newFolderName"
set home_path to path to home folder as string
set work_folder to alias (home_path & "AutomationAppleScript:ScreenShots:")
tell application "Finder"
duplicate every file of work_folder to folder "Archive" of home
end tell
This works for copying to a mounted network volume:
mount volume "afp://compname.local/mountpoint"
tell application "Finder"
duplicate file "MyTextFile.txt" of folder "Documents" of home to disk "mountpoint"
eject "mountpoint"
end tell
tell application "Finder"
make new folder at desktop with properties {name:"folder"}
duplicate POSIX file "/usr/share/doc/bash/bash.html" to result
end tell
POSIX file ((system attribute "HOME") & "/Documents" as text)
tell application "Finder" to result
tell application "Finder" to duplicate (get selection) to desktop replacing yes
-- these are documented in the dictionary of System Events
path to home folder
POSIX path of (path to documents folder)
path to library folder from user domain
path to desktop folder as text
-- getting files as alias list is faster
tell application "Finder"
files of entire contents of (path to preferences folder) as alias list
end tell
The simple way to do it is as below says
set home_path to path to home folder as string
set work_folder to alias (home_path & "AutomationAppleScript:ScreenShots:")
tell application "Finder"
duplicate every file of work_folder to folder "Archive" of home
end tell
I used Chealions shell script solution. Don't forget to make your script file executable with:
sudo chmod u+x scriptFilename
Also remove the space between the = sign in the variable assignments. Wouldn't work with the spaces, for example: newFolderName="Test Folder 2"
If it's a sync you're looking for you can run the following shell script in your AppleScript:
rsync -a /Users/username/folderToBeCopiedFrom /Volumes/folderToBeCopiedTo/