0

这是我想从NSAppleScript运行的终端命令示例

pushd "/Users/myUser/Library/Application Support" && zip -r "/Users/myUser/Desktop/myDataFolder.zip" "myDataFolder" && popd

我的代码:

-(BOOL)runScriptAsAdmin:(NSString*) fullScript
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];

    NSArray *arguments = [NSArray arrayWithObjects:
                          @"-c" ,
                          [NSString stringWithFormat:@"%@", fullScript],
                          nil];


    NSString * output = nil;
    NSString * processErrorDescription = nil;



    NSDictionary *errorInfo = [NSDictionary new];
    NSString *script =  [NSString stringWithFormat:@"do shell script \"%@\" with administrator privileges", fullScript];

    NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
    NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo];

    // Check errorInfo
    if (! eventResult)
    {
        // Describe common errors
        NSString *errorDescription = nil;
        if ([errorInfo valueForKey:NSAppleScriptErrorNumber])
        {
            NSNumber * errorNumber = (NSNumber *)[errorInfo valueForKey:NSAppleScriptErrorNumber];
            if ([errorNumber intValue] == -128)
                errorDescription = @"The administrator password is required to do this.";
        }

        // Set error message from provided message
        if (errorDescription == nil)
        {
            if ([errorInfo valueForKey:NSAppleScriptErrorMessage])
                errorDescription =  (NSString *)[errorInfo valueForKey:NSAppleScriptErrorMessage];
        }

        return NO;
    }
    else
    {
        // Set output to the AppleScript's output
        NSString *output = [eventResult stringValue];
        return YES;

    }

    return NO;
}

调用上述函数:

NSString *command = @"pushd /Users/myUser/Library/Application\ Support && zip -r /Users/myUser/Desktop/myDataFolder.zip myDataFolder && popd";


    TerminalManager* tm = [TerminalManager new];
    if(![tm runScriptAsAdmin:command])
    {
        return NO;
    }

例外:

Expected “"” but found unknown token
4

0 回答 0