Переместить элементы в определенную папку - PullRequest
0 голосов
/ 20 февраля 2019

Я хочу, чтобы действие папки перемещало любые элементы, добавленные в папку рабочего стола, в определенную подпапку.Подпапка генерируется еженедельно каждый понедельник автоматом.На этой неделе эта подпапка называется «Desktop Week 02-18-2019»

Я хочу использовать действия с папками, чтобы при добавлении любого файла на рабочий стол он перемещался в подпапку этой недели.

Насколько я понимаю, мне нужно найти эту подпапку, установить ее в качестве переменной и переместить исходные файлы, которые вызвали действие папки, в эту конкретную подпапку.

Большинство онлайн-решений имеют дело только тогда, когда папка для перемещения в имя уже известна.

Заранее спасибо за помощь

Ответы [ 2 ]

0 голосов
/ 20 февраля 2019

Это пример сценария, который будет перемещать любые новые элементы, добавленные в любую папку, к которой прикреплен этот сценарий.Вам, конечно, придется заменить /Users/USERNAME/Documents/Weeklies на любую папку, в которой вы храните свои еженедельники. Это может быть рабочий стол, поскольку скрипт будет влиять только на новые элементы.

-- move any new items into Weekly subfolder
on adding folder items to theFolder after receiving newItems
    -- determine subfolder name
    set mondayMonday to the weekday of the (current date) as integer
    if mondayMonday is 1 then
        copy the (current date) - 6 * days to mondayDate
    else if mondayMonday is greater than 2 then
        copy the (current date) - (mondayMonday - 2) * days to mondayDate
    end if

    set subFolderName to fillZeroes(month of mondayDate as integer) & "-" & fillZeroes(day of mondayDate) & "-" & year of mondayDate
    set subFolderParent to POSIX file ("/Users/jerry/Documents/Weeklies/")
    set subFolderPath to (subFolderParent as string) & subFolderName

    tell application "Finder"
        --create folder if it doesn't already exist
        if not (exists subFolderPath) then
            make new folder at subFolderParent with properties {name:subFolderName}
        end if

        --copy folder alias subFolderPath to subFolder
        repeat with desktopItem in newItems
            if exists file named (name of desktopItem) in folder subFolderPath then
                set fileName to name of desktopItem as text
                set fileCounter to 1
                set fileNameWithCounter to fileName
                repeat while exists file named fileNameWithCounter in folder subFolderPath
                    --put the counter first, so as not to invalidate any file extension
                    set fileCounter to fileCounter + 1
                    set fileNameWithCounter to (fileCounter as text) & " " & fileName
                end repeat
                --DO NOT MOVE. Renaming will trigger a new folder action
                --moving will cancel the folder action, leaving remaining files on the desktop
                set name of desktopItem to fileNameWithCounter
            else
                move desktopItem to folder subFolderPath
            end if
        end repeat

    end tell
end adding folder items to

--turn any month or day number that is less than ten into two digits with a leading zero
on fillZeroes(theInteger)
    set integerString to theInteger as string
    if the length of integerString is 1 then set integerString to "0" & integerString
    return integerString
end fillZeroes

Хитрость заключается в том, когдафайл уже существует в папке назначения с таким именем;по умолчанию перемещение оставляет элемент на рабочем столе, если существует конфликтующее имя.И единственный другой вариант - перейти с заменой, которая сотрет предыдущий файл.

Но переименование файла на рабочем столе вызовет действие новой папки, оставив все последующие файлы на рабочем столе.Хитрость заключается в том, чтобы переименовать файл , не перемещая его , что позволяет вновь инициированному действию папки обрабатывать его и позволить этому сценарию перейти к остальным элементам.

Обратите внимание, что оба Automatorи AppleScript можно использовать для действий с папками.Это означает, что вам не нужно создавать папку еженедельно;вместо этого он может быть сгенерирован точно в срок, если единственной целью этой папки является сохранение элементов из действия папки.

У вас может быть сценарий Automator, который его генерирует, также будет действие папки;или у вас может быть AppleScript, который перемещает элементы, также генерирует его, как делает этот скрипт.

Если вы хотите, чтобы скрипт не работал, если папка не была сгенерирована, вы бы заменили make new folder at subFolderParent with properties {name:subFolderName} на просто return для выхода из скрипта, если нет папки с соответствующим именем.

0 голосов
/ 20 февраля 2019

Это работает для меня, используя последнюю версию macOS Mojave

Сохраните этот следующий код AppleScript как файл .scpt в папку…./ Пользователи / ТВОЕ ИМЯ / Библиотека / Рабочие процессы / Приложения / Действия с папками.

property moveToFolder : (path to documents folder as text)
property folderNameContains : "Desktop Week"

on adding folder items to theFolder after receiving theNewItems
    if weekday of (current date) is Tuesday then
        set theWeekday to 1
    else if weekday of (current date) is Wednesday then
        set theWeekday to 2
    else if weekday of (current date) is Thursday then
        set theWeekday to 3
    else if weekday of (current date) is Friday then
        set theWeekday to 4
    else if weekday of (current date) is Saturday then
        set theWeekday to 5
    else if weekday of (current date) is Sunday then
        set theWeekday to 6
    else if weekday of (current date) is Monday then
        set theWeekday to 0
    end if

    set moveToFolderCreationDate to short date string of ((current date) - (theWeekday * days))

    tell application "Finder"
        set dateStringForMakeFolder to my shortDateTID(moveToFolderCreationDate, {"/"})
        set a to length of (item 1 of words of dateStringForMakeFolder)
        if a is 1 then set dateStringForMakeFolder to (0 as text) & dateStringForMakeFolder
        try
            make new folder at moveToFolder ¬
                with properties {name:((folderNameContains & " " & dateStringForMakeFolder) as string)}
        end try
        set theFolder to folders of alias moveToFolder whose name contains dateStringForMakeFolder
        move theNewItems to (theFolder as alias) with replacing
    end tell
end adding folder items to

to shortDateTID(someText, delimiterListItems)
    set originalText to someText
    set AppleScript's text item delimiters to delimiterListItems
    set tempText to text items of originalText
    set text item delimiters to "-"
    set cleanedText to tempText as text
end shortDateTID

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...