如何使用 applescript 始终将桌面元素(图标、文件、文件夹)保存在同一位置

How to save your desktop elements (icons, files,folder ) always on the same place with applescript

我们将使用该脚本创建另一个脚本,其中将存储桌面所有元素的位置,创建的脚本将被编译并可用于将之前受保护的所有元素放回原位。

/adesktopsave/deskico.txt 是编译时用到的临时文件。 /adesktopsave/savedicoposition.scpt 编译出来和applescrit一起使用的保存脚本

此处使用的所有名称仅供示例使用。这些名字没有特别的属性.

只需要在使用本脚本前规划好创建一个文件夹即可。这里是: /桌面保存

其他," try 之后的行尾 (\n) “ 还“结束尝试 “ 和 & ”} ")

尊重是非常重要的,这样文本才可用。

    tell application "Finder" to set theList to {name, desktop position} of items of desktop 
try 
do shell script "rm -f /adesktopsave/deskico.txt"

do shell script "echo tell application " & quoted form of (quote & "Finder" & quote) & return & " >>/adesktopsave/deskico.txt" 

end try 

set n to (count (first item of theList))


repeat with i from 1 to n       

set inp to do shell script "echo " & quoted form of (item i of first item of theList)       

set xy to (item i of second item of theList)    

set AppleScript's text item delimiters to ","   

set xyz to do shell script "echo " & xy     
set wxyz to ("{" & xyz & "}
 ")         

set ligne to "try 
" & "set desktop position of item " & quoted form of (quote & inp & quote) & " of desktop to " & quoted form of (wxyz) & "end try 
"       
set ligne to do shell script "echo " & ligne & " >>/adesktopsave/deskico.txt"    

end repeat 

do shell script "echo " & "end tell" & return & " >>/adesktopsave/deskico.txt"

    display dialog "Do you want to save your icons in their current location?" buttons {"Cancel", "Save"} default button 2 with title "Save  the positions of icons"

    if (button returned of result) is "Cancel" then     
set n to do shell script "echo " & n 
else    
do shell script "osacompile -o " & "/adesktopsave/savedicoposition.scpt" & " /adesktopsave/deskico.txt" 
end if 

return n

我们可以将脚本简化为最简单的表达方式。冒着出错的风险可以。

set ligne to ""
do shell script "mkdir -p  /adesktopsave"
tell application "Finder" to set {names, positions} to {name, desktop position} of items of the desktop
set ligne to "tell application \"Finder\"
"
set n to (count names)
set AppleScript's text item delimiters to ","
repeat with i from 1 to n
set ligne to ligne & ("try
" & "set desktop position of item " & (quote & item i of names & quote) & "  to  {" & item i of positions & "}
end try
")
end repeat
set ligne to ligne & ("end tell" & return)
display dialog "Do you want to save your icons in their current location?" buttons {"Cancel", "Save"} default button 2 with title "Save the positions of icons"
  if (button returned of result) is "Cancel" then 
    set n to do shell script "echo " & n
else
  do shell script "osacompile -o " & "/adesktopsave/savedicoposition.scpt  -e  "  & quoted form of ligne
end if
set AppleScript's text item delimiters to ""
tell application "Finder" to open POSIX file "/adesktopsave/savedicoposition.scpt"
return n