How to put a variable in the middle of a pathway? (AppleScript)

applescriptfinder

I am trying to write code that deletes files from a specified location and empties into the trash. If I use the direct string it works but when I try to add a variable it does not. Could someone help show me what I'm doing wrong?

When I tried to look up the error code number at the bottom, it didn't give me much insight.

Valid

tell application "Finder"
        delete (every item of folder "Macintosh HD:Users:sme0219:Pictures:Camera" whose name contains ".png")
end tell

Invalid

tell application "System Events"
    set userName to name of current user
    set compName to name of startup disk
end tell

tell application "Finder"
    delete (every item of folder compName & ":Users:" & userName & ":Pictures:Camera" whose name contains ".png")
end tell

Error Report

error "Can’t get {folder "Applications" of startup disk of application "Finder", folder "Library" of startup disk of application "Finder", folder "System" of startup disk of application "Finder", folder "Users" of startup disk of application "Finder", ":Users:", "sme0219", ":Pictures:Camera"} whose name contains ".png"." number -1728

Best Answer

You need to put parentheses around:

compName & ":Users:" & userName & ":Pictures:Camera"

Example:

(compName & ":Users:" & userName & ":Pictures:Camera")

This concatenates everything within the parentheses as the full path, otherwise Finder just sees:

delete (every item of folder compName & ":Users:" & userName & ":Pictures:Camera" whose name contains ".png")

As:

get every item of folder "Macintosh HD"

Not the entire path.

So, this works:

tell application "System Events"
    set userName to name of current user
    set compName to name of startup disk
end tell

tell application "Finder"
    delete (files of folder (compName & ":Users:" & userName & ":Pictures:Camera") whose name contains ".png")
end tell


Instead of relying on System Events to get that information, you can use the path to (folder) convention to ascertain its path, e.g.:

set targetFolder to (path to pictures folder from user domain) & "Camera" as string

tell application "Finder"
    delete (files of folder targetFolder whose name contains ".png")
end tell

Please take a moment to read the linked document as I believe you'll find it quite informative.

Also note that since you stated code that deletes files in the OP and your code had the potential to delete a folder having a .png extension that every item has bee changes to files with the exception of the line after "otherwise Finder just sees:" in this answer as that line is part of explaining what the issue is that you are having.