Search code examples
macoscocoaapplescriptosx-mavericksapplescript-objc

Call Cocoa-function removeItemAtPath through AppleScript


I want to use the Cocoa-function removeItemAtPath to delete a folder with a path specified in AppleScript part but don't know how to accomplish that through AppleScriptObjC.

Can you help me by giving an example?


Solution

  • Why not just use AppleScript to delete the folder?

    set theFile to "path:to:folder:"
    tell application "System Events"
        delete disk item theFile
    end tell
    

    Edit:

    Based on the comments, you need to do this at the administrator level, and you're able to prompt the user for their credentials. You can put all of that into a shell script.

    If you only need the password, using the current user's user name, this superuser question shows the shell command is:

    echo <password> | sudo -S <command>
    

    Which makes your code:

    set pass to text returned of (display dialog "Enter your password:" default answer "password" with hidden answer)
    do shell script "echo " & quoted form of pass & " | sudo -S rm 'path/to/file'"
    

    If you need to run it under a separate admin user name, you can add in a dialog to get the user name and use the -u flag in your shell script:

    set username to text returned of (display dialog "Enter your username:" default answer "username")
    set pass to text returned of (display dialog "Enter your password:" default answer "password" with hidden answer)
    set shellscript to "echo " & quoted form of pass & " | sudo -S -u " & quoted form of username & " rm 'path/to/file'"