How to batch move PDFs from one folder to another using AppleScript?

26 views Asked by At

I want to automate that scan-files, i.e. pdf files with "-scan" in their filename, are moved to a folder called "Scan". I'm working on an AppleScript code that automates the task of moving PDF files from the "Downloads" folder to a specific folder called "Scan". The PDF files I want to move have names that include "-scan".

When I run my script I get the following error message:

error "Finder got an error: Can’t get folder "/Users/name/Downloads/"." number -1728 from folder "/Users/name/Downloads/"

Here's the script I have so far:

-- Define the path to the download folder
set downloadFolderPath to POSIX path of (path to downloads folder)

-- Define the path to the folder where scanned PDFs will be moved
set scanFolderPath to downloadFolderPath & "Scan/"

-- Get a list of files in the downloads folder
tell application "System Events"
    set downloadFiles to name of every file of folder downloadFolderPath
end tell

-- Iterate through the files and move PDFs with "-scan" in their name to the "Scan" folder
repeat with fileName in downloadFiles
    if fileName contains "-scan" and fileName ends with ".pdf" then
        set filePath to downloadFolderPath & fileName
        tell application "Finder"
            move file (filePath as POSIX file) to folder scanFolderPath
        end tell
    end if
end repeat

1

There are 1 answers

1
vadian On BEST ANSWER

The Finder doesn't know POSIX paths. It you remain with HFS paths you get rid of the other coercion dance too.

- Define the path to the download folder
set downloadFolderPath to (path to downloads folder as text)

-- Define the path to the folder where scanned PDFs will be moved
set scanFolderPath to downloadFolderPath & "Scan:"

-- Get a list of files in the downloads folder
tell application "System Events"
    set downloadFiles to name of every file of folder downloadFolderPath
end tell

-- Iterate through the files and move PDFs with "-scan" in their name to the "Scan" folder
repeat with fileName in downloadFiles
    if fileName contains "-scan" and fileName ends with ".pdf" then
        set filePath to downloadFolderPath & fileName
        tell application "Finder"
            move file filePath to folder scanFolderPath
        end tell
    end if
end repeat

Or shorter

-- Define the path to the download folder
set downloads to path to downloads folder

tell application "Finder"
    move (every file of downloads whose name contains "-scan" and name extension is "pdf") to folder "Scan" of downloads
end tell