How do you in Applescript cp a file to a folder with a variable in name and or prompt for credentials without shell script?

StackOverflow https://stackoverflow.com/questions/16427639

Question

I have an issue where I need it to prompt for admin credentials if needed and cant find a workable solution.

set foo to computer name of (system info)
        set p to (path to desktop)
        set targetFile to "Macintosh HD:private:var:log:system.log:"
        set targetPath to p & "LOGS-I-NEED-" & foo as text

        try
            if ("80" is not in (do shell script "id -G")) then
                tell application "Finder" to duplicate file targetFile to targetPath
                else
                tell application "Finder" to duplicate file targetFile to targetPath
            end if
            on error the error_message number the error_number
            display dialog "Error: " & the error_number & ". " & the error_message & return & "targetFile:" & targetFile & return & return & "targetPath:" & targetPath buttons {"OK"} default button 1

        end try

I have also tried this but dont know how to cp to a folder with a variable in its name.

try
    set foo to computer name of (system info)
    do shell script "sudo cp /Private/var/log/system.log ~/Desktop/{name:LOGS-I-NEED} & foo" with administrator privileges
end try

Either way will work for me.

Thanks Guys!

Était-ce utile?

La solution

quoted form of surrounds strings with single quotes and replaces ' with '\''.

do shell script "d=~/Desktop/LOGS-I-NEED-" & quoted form of (computer name of (system info)) & "
mkdir -p \"$d\"
cp /var/log/system.log \"$d\"" with administrator privileges

You can also get the computer name with systemsetup:

do shell script "d=~/\"Desktop/LOGS-I-NEED-$(systemsetup -getcomputername | sed 's/[^:]*: //')\"
mkdir -p \"$d\"
cp /var/log/system.log \"$d\"" with administrator privileges

If the duplicate command needs root privileges, Finder should show a password dialog. But you could also run a script like this with something like sudo osascript Untitled.scpt:

set d to "LOGS-I-NEED-" & computer name of (system info) as text
tell application "Finder"
    if not (exists folder d of desktop) then
        make new folder at desktop with properties {name:d}
    end if
    duplicate POSIX file "/var/log/system.log" to folder d of desktop
end tell
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top