Search code examples
filedirectoryapplescriptposixrename

AppleScript - Getting error when trying to rename file -10006


With the 2 examples of code below, I want to select a folder and rename the file inside (a .pdf one). The code is pretty simple nevertheless it returns an error -10006. I'm new to AppleScript. I found lots of equivalent requests on the site. The solutions provided do not work for me...

on run
    set Source to (choose folder with prompt "Pick the folder containing the images to process:") as alias
    set newName to "new file name.pdf"
    tell application "Finder"
        try
            set myFile to name of every file of Source as string
            set name of myFile to newName as string
        on error err
            log ("Error in procedure: " & (err as text))
        end try
    end tell
end run

I then tried with a little modification in line 7 (see code below) and the error code is now error number -1728 from file "AD-3.HRYN.pdf"

-1728: The referenced object doesn’t exist. This is a run-time resolution error, such as when attempting to reference a third object when only two objects exist.

on run
    set Source to (choose folder with prompt "Pick the folder containing the images to process:") as alias
    set newName to "new file name.pdf"
    tell application "Finder"
        try
            set myFile to name of every file of Source as string
            set name of file myFile to newName as string
        on error err
            log ("Error in procedure: " & (err as text))
        end try
    end tell
end run

The message in console is: (Error in procedure: Il est impossible de régler name of "AD-3.HRYN.pdf" à "new file name.pdf".)

I have the read/write right on the folder. Have you any ideas?


Solution

  • As I understand it, your folder contains only 1 file and you want rename this file. As you are a beginner, I have added explanatory comments for you. You can, of course, remove them.

    on run
        -- get source folder. The result of Choose Folder is already the Alias
        -- so, no need additional coercion to alias
        set sourceFolder to (choose folder with prompt "Pick the folder containing the images to process:")
        -- set new name variable
        set newName to "new file name.pdf"
        tell application "Finder"
            try
                -- get 1st file's Finder reference
                set myFile to file 1 of sourceFolder
                -- rename it
                set name of myFile to newName
            on error err
                -- err is a string already, no need additional coercion to string 
                log "Error in procedure: " & err
            end try
        end tell
    end run