Даже опытные пользователи Мака иногда ошибаются и делают то, что совсем не планировали. Одна из таких ошибок — случайно отправить в корзину все файлы, найденные Spotlight’ом.
Если вам повезло, и до этого в корзине ничего не было, а все удаленные файлы находились в одной папке, то надо просто зайти в корзину, выделить все и нажать «Put back».
К сожалению, события не всегда складываются настолько удачно, и вы можете оказаться с несколькими сотнями файлов, ранее разбросанных по всему жесткому диску, а теперь печально глядящих на вас из корзины. Восстановить их штатными средствами системы не получится.
Специально для таких случаев я исправил свой старый скрипт, чтобы он мог восстановить максимально возможное число файлов. Логика его работы предельно проста:
- Сначала попытаться восстановить каждую папку (предполагается, что число вложенных уровней не превышает 50);
- Затем поместить каждый файл на свое место с помощью команды «Put back».
Так как все это реализовано с помощью интерфейсных команд, то, во-первых, скрипт работает не быстро, а, во-вторых, надо дать ему доступ к управлению компьютером. Для этого нужно добавить приложение «Put all files back» в список разрешенных в разделе Security & Privacy > Privacy.
Скачать скрипт можно тут.
Кому интересно, ниже приведен исходный код. Буду рад замечаниям и комментариям.
UPD: Пока что скрипт работает только на англоязычной системе. Вы можете временно изменить язык системы на английский (перетащить английский на первое место в списке в разделе настроек «Язык и регион»), запустить скрипт, а затем вернуть настройки обратно.
tell application "Finder" to close every window display dialog "What should the script do if file exists:" buttons {"Replace", "Keep Both", "Skip"} default button 3 set the button_pressed to the button returned of the result if the button_pressed is "Skip" then set the button_pressed to "Stop" end if ignoring application responses tell application "Finder" to set selection to {} end ignoring ## Put back directories at first ## We assume there is maximum a 50-level hierarchy of deleted folders. /must be rewritten somehow/ repeat with depth from 1 to 50 set numberofdirectories to every paragraph of (do shell script "for f in ~/.Trash/*; do if [[ -d $f ]]; then echo $f;fi; done;") set dirCount to count numberofdirectories tell application "System Events" try tell process "Finder" click menu item "Hide Others" of menu 1 of menu bar item "Finder" of menu bar 1 end tell end try # Make the Trash window active. Must be done with mouse click on # Dock icon in order to make the "Put Back" menu item available. tell process "Dock" to click UI element "Trash" of list 1 repeat with i from 1 to dirCount set thefile to text item i of numberofdirectories tell application "Finder" activate try select (POSIX file thefile) of trash folder end try end tell # Delay to allow UI to catch up with script. delay 0.25 # Try to put back the selected item. For some reason doesn't always work. try tell process "Finder" to click menu item "Put Back" of menu "File" of menu bar 1 end try # Delay to allow UI to catch up with script. delay 0.25 # What to do if file already exists try tell process "Finder" click button button_pressed of UI element 0 of window "Copy" end tell end try tell application "Finder" to close every window end repeat end tell end repeat ## Then put back files set numberoffiles to every paragraph of (do shell script "for f in ~/.Trash/*;do if [[ -d $f ]]; then echo \"\" > /dev/null ;else echo $f ;fi; done;") set fileCount to count numberoffiles tell application "System Events" try tell process "Finder" click menu item "Hide Others" of menu 1 of menu bar item "Finder" of menu bar 1 end tell end try # Make the Trash window active. Must be done with mouse click on # Dock icon in order to make the "Put Back" menu item available. tell process "Dock" to click UI element "Trash" of list 1 repeat with i from 1 to fileCount set thefile to text item i of numberoffiles tell application "Finder" activate try select (POSIX file thefile) of trash folder end try end tell # Delay to allow UI to catch up with script. delay 0.25 # Try to put back the selected item. For some reason doesn't always work. try tell process "Finder" to click menu item "Put Back" of menu "File" of menu bar 1 end try # Delay to allow UI to catch up with script. delay 0.25 # What to do if file already exists try tell process "Finder" click button button_pressed of UI element 0 of window "Copy" end tell end try tell application "Finder" to close every window end repeat end tell display dialog "All done. If not all files were recovered try running the script again." buttons {"OK"} default button 1