Move a file to a relative folder

Hi everyone,

I am new to this and english isn´t my native language, so sorry for any mistakes.

I am trying to move a selected file to a folder relative to it location. I have manage to make this work when moving the file to the desktop:

tell application “Finder”
set itemlist to the selection
set theFile to item 1 of itemlist
set theFile to (move theFile to desktop)
end tell

I would like now to replace desktop for something like ~/Final_Project , so I don´t need to tell the scrip where the location of the folder Final_Project is, just tell it that it is on the same location of the file selected, is there a way to accomplish this?

Thanks in advance.

I am relatively new to AppleScript, but I’ve managed to get this to work at moving a file to a Desktop folder named “Final Project”. You’ll need to change that portion of the script to match the location of your folder. Good luck.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

tell application "Finder"
	activate
	set source_file to choose file with prompt "Please choose the Source File"
	set target_folder to "Users:homer:Desktop:Final Project" as alias --Change location as needed
	move source_file to (target_folder)
end tell
1 Like

Hi thanks for your help, but not exactly what I am looking for…

I need the script to move the selected file to a folder call Final_Project which it will be content within the same folder path of the file… but I need the scrip to use a relative path, as I have a lot of folder call Final_Project within many folders. so I cannot give it to the script a full path, just a relative path, to avoid to create as many script as folders I have.

A solution for this will be something like:
~/Final_Project The script need to understand that ~/ need to be replaced for the path of the file.
Not sure if the path of the file could be copy on a variable and then use the variable to replace ~/

Not sure if all of that make sense. I hope it is slight more clear.

Thanks

I’m afraid that what I posted represents pretty much the extent of my limited AppleScript knowledge. But, worry not, as there are a multitude of folks here that are “true experts” with AppleScript and have always assisted me when I was struggling with an issue. I’m sure that in just a couple of days you will have a solution to this issue.

Chavilan. If I understand your request correctly, the following should do what you want:

tell application "Finder"
	set theFiles to (selection as alias list)
	if theFiles is {} then display dialog "A file must be selected" buttons {"OK"} cancel button 1 default button 1
	set theFile to item 1 of theFiles
	set sourceFolder to container of theFile as text
	set targetFolder to sourceFolder & "Final Project:"
	if (exists folder targetFolder) is false then make new folder at sourceFolder with properties {name:"Final Project"}
	try
		move theFile to folder targetFolder
	on error
		display dialog "The selected file already exists in the target folder" buttons {"OK"} cancel button 1 default button 1
	end try
end tell

Since you’re only moving a single file, it’s simple to check the target folder for any item that might have the same name as the one to be relocated. This allows us to remove the try block:

if the name of thefile is in the name of items in the ¬
		folder named targetfolder then return false
	
move thefile to the folder named targetfolder
return true

On a separate note, it’s possible to simplify your implementation a bit by observing that the target folder is in the same containing directory as the selected files that are to be moved.

Finder’s selection will always be a list of file references that are housed in the same containing directory, and this directory will necessarily be the same as Finder’s insertion location. Therefore, your code can be reduced to the following:

tell application "Finder"
        set directory to "Final Project"
        set theFiles to the selection as alias list
        set sourceFolder to insertion location
        set targetFolder to a reference to the ¬
                sourceFolder's folder directory
        if not (exists the targetFolder) then make new ¬
                folder at sourceFolder with properties ¬
                {name:directory}
        move theFiles to the targetFolder replacing no
end tell

(It doesn’t actually look that reduced, but that’s my whacky obsessiveness over formatting.)

1 Like

FWIW, I tested both scripts on my system (Sonoma 14.7) and both worked perfectly (once I understood that the file had to actually be “selected” in Finder).

1 Like

on run

tell application “Finder”

set selectedItems to selection

if selectedItems is {} then

display dialog “No file selected. Please select a file first.” buttons {“OK”} default button “OK”

return

end if

end tell

– Prompt user for the keyword to search for the nearest target folder

set folderName to text returned of (display dialog “Enter the name of the target folder:” default answer “”)

– Use mdfind to locate folders named based on user input

tell application “System Events”

set foundFolders to paragraphs of (do shell script “mdfind 'kMDItemKind == "Folder" && kMDItemFSName == "” & folderName & “"'”)

end tell

if foundFolders is {} then

display dialog “No '” & folderName & “’ folder found.” buttons {“OK”} default button “OK”

return

end if

– Loop through each selected file and find its closest folder

repeat with selectedItem in selectedItems

set selectedItemPath to POSIX path of (selectedItem as alias)

set longestCommonPrefix to 0

set closestFolder to missing value

– Compare each found folder path to the selected item path

repeat with aFolder in foundFolders

set commonPrefixLength to my findCommonPrefixLength(selectedItemPath, aFolder)

if commonPrefixLength > longestCommonPrefix then

set longestCommonPrefix to commonPrefixLength

set closestFolder to aFolder

end if

end repeat

– Check if we found a folder

if closestFolder is not missing value then

tell application “Finder”

set selectedItemAlias to selectedItem as alias

set posixPathOfItem to POSIX path of selectedItemAlias

– Retrieve the file name safely

set fileName to name of (selectedItemAlias)

set destinationPath to closestFolder & “/” & fileName

– Handle filename conflict by appending a unique number

set counter to 1

set baseName to fileName

set ext to name extension of selectedItemAlias

if ext is not “” then

set baseName to text 1 thru ((length of fileName) - (length of ext) - 1) of fileName

end if

– Loop to avoid overwriting files in the destination folder

repeat while (do shell script "test -e " & quoted form of (closestFolder & “/” & fileName) & “; echo $?”) is “0”

set destinationPath to closestFolder & “/” & baseName & “-” & counter & “.” & ext

set counter to counter + 1

end repeat

– Move the file to the closest folder

do shell script "mv " & quoted form of posixPathOfItem & " " & quoted form of destinationPath

display notification “File '” & fileName & “’ moved successfully to the nearest folder.”

end tell

else

display dialog “No closest '” & folderName & "’ folder found for " & fileName buttons {“OK”} default button “OK”

end if

end repeat

end run

– Function to find the length of the longest common prefix

on findCommonPrefixLength(path1, path2)

set path1Components to my splitString(path1, “/”)

set path2Components to my splitString(path2, “/”)

if (length of path1Components) < (length of path2Components) then

set minLength to length of path1Components

else

set minLength to length of path2Components

end if

set indexFile to 0

repeat with i from 1 to minLength

if item i of path1Components is not item i of path2Components then

return indexFile

end if

set indexFile to indexFile + 1

end repeat

return indexFile

end findCommonPrefixLength

– Function to split a string by a delimiter

on splitString(theString, theDelimiter)

set AppleScript’s text item delimiters to theDelimiter

set theArray to every text item of theString

set AppleScript’s text item delimiters to “”

return theArray

end splitString

This is more generic code to move to nearest target folder relative to source location. Kindly review and see if it is useful and how it can be improved further

tell application "Finder"
	set selectedItems to selection
	if selectedItems is {} then
		display dialog "No file selected. Please select a file first." buttons {"OK"} default button "OK"
		return
	end if
end tell

-- Prompt user for the keyword to search for the nearest target folder
set folderName to text returned of (display dialog "Enter the name of the target folder:" default answer "")

-- Use mdfind to locate folders named based on user input
tell application "System Events"
	set foundFolders to paragraphs of (do shell script "mdfind 'kMDItemKind == \"Folder\" && kMDItemFSName == \"" & folderName & "\"'")
end tell

if foundFolders is {} then
	display dialog "No '" & folderName & "' folder found." buttons {"OK"} default button "OK"
	return
end if

-- Loop through each selected file and find its closest folder
repeat with selectedItem in selectedItems
	set selectedItemPath to POSIX path of (selectedItem as alias)
	set longestCommonPrefix to 0
	set closestFolder to missing value
	
	-- Compare each found folder path to the selected item path
	repeat with aFolder in foundFolders
		set commonPrefixLength to my findCommonPrefixLength(selectedItemPath, aFolder)
		if commonPrefixLength > longestCommonPrefix then
			set longestCommonPrefix to commonPrefixLength
			set closestFolder to aFolder
		end if
	end repeat
	
	-- Check if we found a folder
	if closestFolder is not missing value then
		tell application "Finder"
			set selectedItemAlias to selectedItem as alias
			set posixPathOfItem to POSIX path of selectedItemAlias
			
			-- Retrieve the file name safely
			set fileName to name of (selectedItemAlias)
			set destinationPath to closestFolder & "/" & fileName
			
			-- Handle filename conflict by appending a unique number
			set counter to 1
			set baseName to fileName
			set ext to name extension of selectedItemAlias
			if ext is not "" then
				set baseName to text 1 thru ((length of fileName) - (length of ext) - 1) of fileName
			end if
			
			-- Loop to avoid overwriting files in the destination folder
			repeat while (do shell script "test -e " & quoted form of (closestFolder & "/" & fileName) & "; echo $?") is "0"
				set destinationPath to closestFolder & "/" & baseName & "-" & counter & "." & ext
				set counter to counter + 1
			end repeat
			
			-- Move the file to the closest folder
			do shell script "mv " & quoted form of posixPathOfItem & " " & quoted form of destinationPath
			display notification "File '" & fileName & "' moved successfully to the nearest folder."
		end tell
	else
		display dialog "No closest '" & folderName & "' folder found for " & fileName buttons {"OK"} default button "OK"
	end if
end repeat

-- Function to find the length of the longest common prefix
on findCommonPrefixLength(path1, path2)
	set path1Components to my splitString(path1, "/")
	set path2Components to my splitString(path2, "/")
	if (length of path1Components) < (length of path2Components) then
		set minLength to length of path1Components
	else
		set minLength to length of path2Components
	end if
	set indexFile to 0
	repeat with i from 1 to minLength
		if item i of path1Components is not item i of path2Components then
			return indexFile
		end if
		set indexFile to indexFile + 1
	end repeat
	return indexFile
end findCommonPrefixLength

-- Function to split a string by a delimiter
on splitString(theString, theDelimiter)
	set AppleScript's text item delimiters to theDelimiter
	set theArray to every text item of theString
	set AppleScript's text item delimiters to ""
	return theArray
end splitString

Posted with correct format for the code

My Take on the above script, I wish I could use predicate

tell application "Finder"
	
	-- Target Front Finder window
	set sourceFolder to POSIX path of (target of window 1 as alias)
	
	set selectedItems to selection
	if selectedItems is {} then
		display dialog "No file selected. Please select a file first." buttons {"OK"} default button "OK"
		return
	end if
end tell

-- Prompt user for the keyword to search for the nearest target folder
set folderName to text returned of (display dialog "Enter the name of the target folder:" default answer "")


-- Use mdfind to locate folders named based on user input
tell application "System Events"
	set foundFolders to paragraphs of (do shell script "mdfind -onlyin " & quoted form of sourceFolder & " 'kMDItemKind == \"Folder\" && kMDItemFSName == \"*" & folderName & "*\"'")
end tell

if foundFolders is {} then
	display dialog "No '" & folderName & "' folder found." buttons {"OK"} default button "OK"
	return
end if

-- Extract just the folder names for display
set folderNames to {}
set folderPathMap to {}
tell application "System Events"
	repeat with folderPath in foundFolders
		set folderName to name of (disk item folderPath)
		set end of folderNames to folderName
		set end of folderPathMap to folderPath -- Keep the full path for later use
	end repeat
end tell

-- Let the user select the actual folder from the names
set selectedFolderName to choose from list folderNames with prompt "Select the target folder:" without multiple selections allowed
if selectedFolderName is false then return -- If user cancels the selection

-- Find the full path of the selected folder
set closestFolder to ""
repeat with i from 1 to count folderNames
	if (item i of folderNames) is equal to item 1 of selectedFolderName then
		set closestFolder to item i of folderPathMap -- Get the corresponding full path
		exit repeat
	end if
end repeat

-- Loop through each selected file and find its closest folder
repeat with selectedItem in selectedItems
	set selectedItemPath to POSIX path of (selectedItem as alias)
	set selectedItemAlias to selectedItem as alias
	tell application "Finder" to set fileName to name of selectedItemAlias
	set destinationPath to closestFolder & "/" & fileName
	
	-- Check if the file exists before moving it
	set fileExists to (do shell script "test -e " & quoted form of selectedItemPath & "; echo $?")
	if fileExists is "0" then
		-- Handle filename conflict by appending a unique number
		set counter to 1
		set baseName to fileName
		tell application "Finder" to set ext to name extension of selectedItemAlias
		if ext is not "" then
			set baseName to text 1 thru ((length of fileName) - (length of ext) - 1) of fileName
		end if
		
		-- Loop to avoid overwriting files in the destination folder
		repeat while (do shell script "test -e " & quoted form of destinationPath & "; echo $?") is "0"
			-- Increment the counter and create a new destination path
			set destinationPath to closestFolder & "/" & baseName & "-" & counter & "." & ext
			set counter to counter + 1
		end repeat
		
		-- Move the file to the closest folder
		do shell script "mv " & quoted form of selectedItemPath & " " & quoted form of destinationPath
		display notification "File '" & fileName & "' moved successfully to the nearest folder."
	else
		display dialog "File '" & fileName & "' does not exist." buttons {"OK"} default button "OK"
	end if
end repeat

Here is cut paste version using Peavine’s predicate handler

use framework "Foundation"
use scripting additions

tell application "Finder"
	
	-- Target Front Finder window
	set sourceFolder to POSIX path of (target of window 1 as alias)
	-- set sourceFolder to POSIX path of (choose folder)
	
	set selectedItems to selection
	if selectedItems is {} then
		display dialog "No file selected. Please select a file first." buttons {"OK"} default button "OK"
		return
	end if
end tell

-- search is case insensitive
-- Prompt user for the keyword to search for the target folder
set searchString to text returned of (display dialog "Enter search String of the target folder:" default answer "")


set {foundFolders, theFiles} to getFoldersAndFiles(sourceFolder, searchString)

if foundFolders is {} then
	display dialog "No '" & foundFolders & "' folder found." buttons {"OK"} default button "OK"
	return
end if

-- Extract just the folder names for display
set folderNames to {}
set folderPathMap to {}
tell application "System Events"
	repeat with folderPath in foundFolders
		set folderName to name of (disk item folderPath)
		set end of folderNames to folderName
		set end of folderPathMap to folderPath -- Keep the full path for later use
	end repeat
end tell

-- Let the user select the actual folder from the names
set selectedFolderName to choose from list folderNames with prompt "Select the target folder:" without multiple selections allowed
if selectedFolderName is false then return -- If user cancels the selection

-- Find the full path of the selected folder
set closestFolder to ""
repeat with i from 1 to count folderNames
	if (item i of folderNames) is equal to item 1 of selectedFolderName then
		set closestFolder to item i of folderPathMap -- Get the corresponding full path
		exit repeat
	end if
end repeat

-- Loop through each selected file and find its closest folder
repeat with selectedItem in selectedItems
	set selectedItemPath to POSIX path of (selectedItem as alias)
	set selectedItemAlias to selectedItem as alias
	tell application "Finder" to set fileName to name of selectedItemAlias
	set destinationPath to closestFolder & "/" & fileName
	
	-- Check if the file exists before moving it
	set fileExists to (do shell script "test -e " & quoted form of selectedItemPath & "; echo $?")
	if fileExists is "0" then
		-- Handle filename conflict by appending a unique number
		set counter to 1
		set baseName to fileName
		tell application "Finder" to set ext to name extension of selectedItemAlias
		if ext is not "" then
			set baseName to text 1 thru ((length of fileName) - (length of ext) - 1) of fileName
		end if
		
		-- Loop to avoid overwriting files in the destination folder
		repeat while (do shell script "test -e " & quoted form of destinationPath & "; echo $?") is "0"
			-- Increment the counter and create a new destination path
			set destinationPath to closestFolder & "/" & baseName & "-" & counter & "." & ext
			set counter to counter + 1
		end repeat
		
		-- Move the file to the closest folder
		do shell script "mv " & quoted form of selectedItemPath & " " & quoted form of destinationPath
		display notification "File '" & fileName & "' moved successfully to the nearest folder."
	else
		display dialog "File '" & fileName & "' does not exist." buttons {"OK"} default button "OK"
	end if
end repeat

on getFoldersAndFiles(theFolder, searchString)
	-- https://www.macscripter.net/t/filtering-entire-contents-of/74683/11 
	set fileManager to current application's NSFileManager's defaultManager()
	set theFolder to current application's |NSURL|'s fileURLWithPath:theFolder
	set theKeys to {current application's NSURLPathKey, current application's NSURLIsPackageKey, current application's NSURLIsDirectoryKey}
	set folderContents to (fileManager's enumeratorAtURL:theFolder includingPropertiesForKeys:theKeys options:6 errorHandler:(missing value))'s allObjects()
	set thePredicate to current application's NSPredicate's predicateWithFormat_("lastPathComponent CONTAINS[c] %@", searchString)
	set folderContents to folderContents's filteredArrayUsingPredicate:thePredicate
	set theFolders to current application's NSMutableArray's new()
	repeat with anItem in folderContents
		(theFolders's addObject:(anItem's resourceValuesForKeys:theKeys |error|:(missing value)))
	end repeat
	set thePredicate to current application's NSPredicate's predicateWithFormat_("%K == YES AND %K == NO", current application's NSURLIsDirectoryKey, current application's NSURLIsPackageKey)
	set theFolders to theFolders's filteredArrayUsingPredicate:thePredicate
	set theFolders to (theFolders's valueForKey:(current application's NSURLPathKey))
	set theFiles to (folderContents's valueForKey:"path")'s mutableCopy()
	theFiles's removeObjectsInArray:theFolders
	return {theFolders as list, theFiles as list}
end getFoldersAndFiles
--==========================================================-- 

Cut Paste Script :slight_smile:

use framework "Foundation"
use scripting additions

tell application "Finder"
	-- Target Front Finder window
	set sourceFolder to POSIX path of (target of window 1 as alias)
	set selectedItems to selection
	if selectedItems is {} then
		display dialog "No file selected. Please select a file first." buttons {"OK"} default button "OK"
		return
	end if
end tell

-- Prompt user for the keyword to search for the target folder
set searchString to text returned of (display dialog "Enter search string for the target folder:" default answer "")

-- Predicate handler to get folders and files
set {foundFolders, theFiles} to getFoldersAndFiles(sourceFolder, searchString)

if foundFolders is {} then
	display dialog "No folders found." buttons {"OK"} default button "OK"
	return
end if

-- Extract folder names for display
set folderNames to {}
set folderPathMap to {}

repeat with folderPath in foundFolders
	set folderURL to (current application's |NSURL|'s URLWithString:folderPath)
	set folderName to folderURL's lastPathComponent() as text
	set end of folderNames to folderName
	set end of folderPathMap to folderPath -- Keep the full path for later use
end repeat

-- Select the actual folder from the names
set selectedFolderName to choose from list folderNames with prompt "Select the target folder:" without multiple selections allowed
if selectedFolderName is false then return -- If user cancels the selection

-- Find the full path of the selected folder
set matchFolder to ""
repeat with i from 1 to count folderNames
	if (item i of folderNames) is equal to item 1 of selectedFolderName then
		set matchFolder to item i of folderPathMap -- Get the corresponding full path
		exit repeat
	end if
end repeat

-- Loop through each selected file and find its closest folder
repeat with selectedItem in selectedItems
	set selectedItemPath to POSIX path of (selectedItem as alias)
	set selectedItemAlias to selectedItem as alias
	tell application "Finder" to set fileName to name of selectedItemAlias
	
	-- Create destination Path, Check for end "/"
	set destinationPath to matchFolder & "/" & fileName
	if matchFolder ends with "/" then
		set destinationPath to matchFolder & fileName
	end if
	
	-- Check if the destination folder exists
	if not (do shell script "test -d " & quoted form of matchFolder & "; echo $?") is "0" then
		display dialog "The destination folder does not exist." buttons {"OK"} default button "OK"
		return
	end if
	
	-- Check if the file exists before moving it
	if fileExists(selectedItemPath) then
		-- Handle filename conflict by appending a unique number
		set counter to 1
		set baseName to fileName
		tell application "Finder" to set ext to name extension of selectedItemAlias
		if ext is not "" then
			set baseName to text 1 thru ((length of fileName) - (length of ext) - 1) of fileName
		end if
		
		-- Loop to avoid overwriting files in the destination folder
		repeat while fileExists(destinationPath)
			set destinationPath to matchFolder & "/" & baseName & "-" & counter & "." & ext
			set counter to counter + 1
		end repeat
		
		-- Copy and replace the file using the copyAndReplace handler
		set {copySuccess, copyError} to copyAndReplace(selectedItemPath, destinationPath)
		if copySuccess then
			display notification "File '" & fileName & "' moved successfully to the Selected folder."
		else
			display dialog "Error moving file: " & (copyError's localizedDescription) buttons {"OK"} default button "OK"
		end if
	else
		display dialog "File '" & fileName & "' does not exist." buttons {"OK"} default button "OK"
	end if
end repeat

-- Get folders and files
on getFoldersAndFiles(theFolder, searchString)
	set fileManager to current application's NSFileManager's defaultManager()
	set theFolder to current application's |NSURL|'s fileURLWithPath:theFolder
	set theKeys to {current application's NSURLPathKey, current application's NSURLIsPackageKey, current application's NSURLIsDirectoryKey}
	set folderContents to (fileManager's enumeratorAtURL:theFolder includingPropertiesForKeys:theKeys options:6 errorHandler:(missing value))'s allObjects()
	
	-- Filter the contents based on the search string
	set thePredicate to current application's NSPredicate's predicateWithFormat_("lastPathComponent CONTAINS[c] %@", searchString)
	set filteredContents to folderContents's filteredArrayUsingPredicate:thePredicate
	
	-- Initialize lists for folders and files
	set theFolders to {}
	set theFiles to {}
	
	repeat with anItem in filteredContents
		set resourceValues to (anItem's resourceValuesForKeys:theKeys |error|:(missing value))
		if resourceValues's NSURLIsDirectoryKey as boolean then
			-- Convert to POSIX path and store
			set end of theFolders to (anItem's |path| as text)
		else if resourceValues's NSURLIsPackageKey as boolean is false then
			-- Convert to POSIX path and store
			set end of theFiles to (anItem's |path| as text)
		end if
	end repeat
	
	return {theFolders, theFiles}
end getFoldersAndFiles

on fileExists(filePath)
	-- Check if the file exists using a shell command
	set fileCheck to do shell script "test -e " & quoted form of filePath & "; echo $?"
	return fileCheck is "0"
end fileExists

on copyAndReplace(sourceFile, destinationFile)
	-- https://www.macscripter.net/t/copy-a-file-with-an-existing-file-at-the-target/72902/3 
	set sourceURL to current application's |NSURL|'s fileURLWithPath:sourceFile
	set destinationURL to current application's |NSURL|'s fileURLWithPath:destinationFile
	set fileManager to current application's NSFileManager's defaultManager
	set {theResult, theError} to fileManager's replaceItemAtURL:destinationURL withItemAtURL:sourceURL backupItemName:(missing value) options:0 resultingItemURL:(missing value) |error|:(reference)
end copyAndReplace

Pankajsz raises an interesting question, which is how to get the folder with a particular name that is most proximate (measured by path length) to the containing folder of a source file. Pankajsz uses mdfind and text item delimiters, which is a reliable approach, but I wondered what the alternatives are.

I tested two Finder solutions but the fastest one took 230 milliseconds to run, and this was with a folder that only contained 142 subfolders. Also, the scripts rely on a sort order which may not be reliable.

The following ASObjC solution took 7 milliseconds to run. This script doesn’t check to see if theFolders are in fact all folders, because the likelihood they are not is small, and because this potential error can be caught later in the script. There’s also the question of how the script should decide between two folders that are equidistant from the source folder, and this issue is not addressed.

use framework "Foundation"
use scripting additions

set closestFolder to getClosestFolder("/Users/Robert/Records/Test File.txt", "2018") --parameters are the source file and target folder name
set thePath to closestFolder's |path|() as text --just for testing

on getClosestFolder(theFile, folderName)
	set fileManager to current application's NSFileManager's defaultManager()
	set theFile to current application's |NSURL|'s fileURLWithPath:theFile
	set sourceFolder to theFile's URLByDeletingLastPathComponent()
	set folderContents to (fileManager's enumeratorAtURL:sourceFolder includingPropertiesForKeys:{} options:6 errorHandler:(missing value))'s allObjects() --option 6 skips hidden items and package contents
	set thePredicate to current application's NSPredicate's predicateWithFormat_("lastPathComponent == %@", folderName)
	set theFolders to folderContents's filteredArrayUsingPredicate:thePredicate
	--if desired insert code to check if the contents of theFolders are in fact all folders
	set shortestPath to 500 --500 is an arbitrary number
	repeat with aFolder in theFolders
		set pathCount to (aFolder's pathComponents())'s |count|()
		if pathCount is less than shortestPath then
			set closestFolder to contents of aFolder
			set shortestPath to pathCount
		end if
	end repeat
	return closestFolder
end getClosestFolder

One208’s scripts prompt the user to select the target folder, and this is probably the most reliable approach overall.

1 Like