Scripting

RSS for tag

Scripting allows you to automate complex, repetitive, and time-consuming tasks by writing scripts that interact with apps, processes, and the operating system.

Posts under Scripting tag

27 Posts
Sort by:
Post not yet marked as solved
1 Replies
29 Views
We have been trying to understand why the Mac OS Terminal, when invoked with open, does not pass along the environment variables. How to reproduce? Create a new file /tmp/example.sh #!/bin/sh echo "SAMPLE_ENV='$SAMPLE_ENV'" SAMPLE_ENV=123 open -a Terminal /tmp/example.command Only prints: SAMPLE_ENV='' Even when using SAMPLE_ENV=123 open --env SAMPLE_ENV=1234 -a Terminal /tmp/example.sh    it will only print SAMPLE_ENV='' We know for sure that this was working several years ago. Why was the feature removed or is this a bug? Any workaround? Is there a workaround on how to launch a script in a new Terminal Window while passing the environment variables correctly? Related https://stackoverflow.com/questions/69768133/react-native-envs-are-undefined-in-metro-bundlers-config-file-when-bundling/73036234
Posted
by yoshi1337.
Last updated
.
Post not yet marked as solved
0 Replies
67 Views
We have a project that compiles an app for both x64 and arm64 Mac machines. This build is done via Visual Studio MSBuild with specific RIDs and Mac native code via xcode. Using the 'packages' application we build an distribution package, which contains the two pkgs for the specific architectures. The project contains settings to pick the correct PKG according to the architecture running the installation ('packages' will include a JavaScript script in the Distribution file for this). This all works just fine when running the final PKG manually. But when deploying via Intune as LOB this doesn't work well. It seems Intune will skip the complete Distribution file and will install all the PKGs included in to distribution package. The logfile shows that both x64 and arm64 are installed Install.log This will result in the x64 to be installed, and being overwritten by the arm64 installation. And a non-functional app on a x64 based Mac. We edited the preinstall.sh for both packages and do another architecture check and error-out when running on a wrong platform; but that doesn't work either: Intune will cancel the whole installation transaction when one pkg fails. Resulting in a non-installed package. What would be a good way to create an universal installation/distribution package with both architectures which would be able to be deployed via intune?
Posted
by JSdeJong.
Last updated
.
Post not yet marked as solved
0 Replies
58 Views
I am trying to get the title of the slides.  But it is not working with apple script, can anyone please help me with this? This is the code I have written in AppleScript. tell application "Keynote" activate tell the first slide set slideone to first slide of document 1 set mytitlename to title of slideone end tell end tell
Posted Last updated
.
Post not yet marked as solved
0 Replies
97 Views
Hello, i am currently trying to implement a pre build script execution in a package. I am using this tutorial to implement it. But it only shows how to use the pre build feature with an already existing feature. I want to execute a skript on my pc every time i build the project. I can't use apples prebuild skript feature in the build settings because it is a package. Right now my code looks like this: import Foundation import OSLog import PackagePlugin @main struct GenerateLocalizer: BuildToolPlugin {     do {       let commandlineOutput = try shell("./testScript.sh")     } catch {     }     return [.prebuildCommand(displayName: "Generate Strings", executable: PackagePlugin.Path("./scrips/generate_strings.sh"), arguments: [], outputFilesDirectory: target.directory)]   }   func shell(_ command: String) throws -> String {     let task = Process()     let pipe = Pipe()     task.standardOutput = pipe     task.standardError = pipe     task.arguments = [command]     os_log("%{public}@", log: log, task.arguments?.joined(separator: " ") ?? "not found")     task.launchPath = "/bin/zsh"     task.standardInput = nil     try task.run()     let data = pipe.fileHandleForReading.readDataToEndOfFile()     let output = String(data: data, encoding: .utf8)!     return output   } } and my Package file looks something like that       name: "CustomSdk",       dependencies: ["CustomSdk-Objc"],       path: "CustomSdk",       exclude: ["Info.plist", "CustomSdk.podspec"],       plugins: [         .plugin(name: "GenerateLocalizer")       ]     ),     .plugin(name: "GenerateLocalizer",         capability: .buildTool(),         dependencies: ["CustomSdk-Objc"]     ) It gets called properly but when want to write files in my "testScript.sh" it only says: Operation not permitted. Anyone got any ideas how to fix this or is there another way to utitlize custom scripts with custom packages? Greetings Ben
Posted
by benkai.
Last updated
.
Post not yet marked as solved
0 Replies
97 Views
We've been looking for a while for a solution to updating package dependencies from the command line. Does Xcode 14 provide a way to do it? I've been searching and haven't seen anything. Anyone saw something? We've had xcodebuild -resolvePackageDependencies for a while, but as many people point out here and in Stack Overflow, this option does not actually update the dependencies like the Update to Latest Package Versions menu command does in Xcode. The goal is to have an automated way to keep dependencies up-to-date, so we can run a script nightly that produces a PR which someone on the team can verify before merging.
Posted Last updated
.
Post marked as solved
10 Replies
6.5k Views
Hi guys,someone else has encountered this error with XCode 10 and Mojave? A simple fragment of code, that works fine on applescript, fail during the compilation on XCode with the error "Not authorized to send Apple Events to System Events. (error -1743).on applicationWillFinishLaunching_(aNotification) tell application "System Events" -- any fragment of code that comes to mind tell appearance preferences set dark mode to not dark mode end tell end tell end applicationWillFinishLaunching_ I have searched in google but I have not found anything,thanks for help
Posted
by malacate.
Last updated
.
Post marked as Apple Recommended
1.1k Views
I have started to experiment with Xcode UI testing and with in my first few tests, I am observing that the app state is being retained between tests.How I kill the app completely?http://masilotti.com/xctest-documentation/Classes/XCUIApplication.html#//api/name/terminatecommand only seems to put the app in background/suspend it
Posted
by smalugu.
Last updated
.
Post marked as Apple Recommended
1.2k Views
Hello,I have unique requirement where i want to use automation frameworks such as XCUITest etc. to be able to automate 3rd party apps. I know that the XCode 8 now has native support however so far from what i can tell it only works if you have access to source code?In my case the app is available as a binary and there is no source code access available/possible? In this case any recommendations how Ui based autoamtion can be built and used?Previoulsy i was able to use UiAutomation framework but that has been depcreated in latest XCode. In the new XCUITest framework I havent been able to sort out how to target a 3rd party app installed on the iPhone and automate that.Any help would be appreciated.Thanks
Posted
by sbhardwaj.
Last updated
.
Post marked as Apple Recommended
1.4k Views
Has anyone been able to find any documentation on XCUITest? I haven't had much success with it. I've watched the video a few times and it doesn't work as easily as is shown. I can't find any other sources of documentation other than reading the few comments in a couple of header files. I'm so frustrated...
Posted
by jos.
Last updated
.
Post marked as solved
3 Replies
1.1k Views
This is so strange I'm at a loss. Background: I am a DevOps engineer validating that our iOS build scripts can run via Bamboo on new Mac mini M1 machines. Out of the box, these machines are running Monterey, while our in-use machines are all still on Big Sur. Tldr; After modifying security permissions for our custom CI keychain so it's accessible by Xcode's CLI tools (specifically, the codesign and security utilities) the "xcodebuild archive" command we run fails with NO logged errors, causing bamboo to fail the build. However, the "failed" command produces a VALID xcarchive file. If I force the archive step to exit with a zero status, the subsequent "xcodebuild exportArchive" step successfully generates a valid .ipa that can be submitted to Testflight and run as expected. I've never seen anything like this. Details: Initially, our builds were failing with codesigning errors related to the CLI tools interacting with our custom keychain (we use a custom keychain so Bamboo only has access to the codesigning assets it needs, this is best practice, at least up til now.) We could build on the new Mac mini with Xcode IDE just fine, and we could even build from the commandline on the new Mac mini. However, running the same commands via ssh to the new Mac mini from my local machine produced the same error bamboo was getting. We were getting errors like this: 23-Mar-2022 13:35:58 Warning: unable to build chain to self-signed root for signer "Apple Development: Elizabeth Goldstein (XXXXXXX)" 23-Mar-2022 13:35:58 /Users/bamboo/agent-home/xml-data/build-dir/path/to/Build/Products/QA-iphoneos/Shared.framework: errSecInternalComponent 23-Mar-2022 13:35:58 Command CodeSign failed with a nonzero exit code We were already unlocking the keychain as part of the build script, and the private key was set to "Allow all access" for outside applications (two common issues that might raise this error.) Finally, I rebuilt the system keychain by first deleting then manually re-importing Apple's root signing certificates from terminal like this: sudo security import ./AppleWWDRCA.cer -k /Library/Keychains/System.keychain -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild sudo security import ./AppleWWDRCAG3.cer -k /Library/Keychains/System.keychain -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild Then I deleted and re-imported my company's signing assets into our custom keychain like this: security import ./appstore-cert.p12 -k /Users/bamboo/Library/Keychains/our-ci.keychain-db -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild security import ./dev-cert.p12 -k /Users/bamboo/Library/Keychains/our-ci.keychain-db -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild So now, there are zero errors in the log that I can find, but bamboo still fails when we run these commands: /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -workspace OUR-APP.xcworkspace -scheme iPhoneApp-QA clean build -configuration QA -derivedDataPath output -sdk iphoneos OTHER_CFLAGS="-fembed-bitcode" ENABLE_BITCODE=YES BITCODE_GENERATION_MODE=bitcode /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -workspace OUR-APP.xcworkspace -scheme iPhoneApp-QA -sdk iphoneos -configuration QA -derivedDataPath output archive -archivePath build.xcarchive OTHER_CFLAGS="-fembed-bitcode" ENABLE_BITCODE=YES BITCODE_GENERATION_MODE=bitcode If I change it to /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -workspace OUR-APP.xcworkspace -scheme iPhoneApp-QA -sdk iphoneos -configuration QA -derivedDataPath output archive -archivePath build.xcarchive OTHER_CFLAGS="-fembed-bitcode" ENABLE_BITCODE=YES BITCODE_GENERATION_MODE=bitcode || exit 0 The final exportArchive command generates a valid .ipa Any help or ideas would be greatly appreciated, since of course that's not a viable workaround, nor is pinning our OS to Big Sur forever, and we need to scale up our CI system. Thank you for reading this far!
Posted
by LizCira.
Last updated
.
Post not yet marked as solved
0 Replies
214 Views
Hi! I'm looking to create a system utility to apply an openGL shader (or Metal?) to the window that the user is focused on (or the screen), ideally with a keyboard shortcut. From what I can tell, applying OpenGL shaders or pixel level modifications to the whole screens at a time is possible (e.g. BlackLight by Michel Fortin). Any pointers to this kind of thing would be great. Combining Automator workflows with some system-level code seems like it would do the trick but I'm not sure where to start. Update: It looks like CGColorSpace might be helpful for applying color transforms to windows. Perhaps there's a way to make a swift app similar to Rectangle that could modify these CoreGraphics elements instead of the coordinates / transform ones? Thanks for the help, Jack
Posted Last updated
.
Post not yet marked as solved
1 Replies
610 Views
In the past I used this script as groundwork for a little helper which swaps the Modifier Keys (CMD, OPT, CTRL) for me, when a specific application getting focused and unfocused. With MacOS 12.3 Apple finally removed Python2 Not a big deal, if you reinstall it via Homebrew and update all your Python scripts. But what is about Apple related modules like NSWorkspace from AppKit? Code: try: from AppKit import NSWorkspace except ImportError: print "Can't import AppKit -- maybe you're running python from brew?" print "Try running with Apple's /usr/bin/python instead." exit(1) This code returns reasonably the print-message. Question Is this not available anymore? Because the homebrew version can't find this and Python3 seems also not to know it. Is NSWorkspace for Python now deprecated?
Posted
by novek.
Last updated
.
Post not yet marked as solved
2 Replies
750 Views
i'm tying to create a custom LDAP configuration in a swift script, something similar to this without using python: https://github.com/Yohan460/Programmatic-OD-Python-Binding my script fails at the custom call - not sure if the issue is my data types or that the functions used in the python example don't exactly translate. any help is appreciated, thanks in advance! p.s - i'm a total swift n00b #!/usr/bin/swift import Foundation import OpenDirectory let fileName = "ldap.plist" let configData = try String(contentsOfFile: fileName) let config = Data(configData.utf8) let odSesh = ODSession.default() let configNode = try! ODNode(session: odSesh,type: ODNodeType(kODNodeTypeConfigure)) let outNode = try! configNode.customCall(99991, send: config)
Posted Last updated
.
Post not yet marked as solved
5 Replies
3.4k Views
Anyone had issues with running scripts on Big Sur? I get a command not found error and I’m guessing its a toggle or a command or a back age that needs to be added to enable it or its blocked by default for security reasons?
Posted
by pinni74.
Last updated
.
Post not yet marked as solved
0 Replies
368 Views
Does anyone know how to automate the install of Xcode Command Line Tools? Bonus points for doing it in a supportable Apple method, and if possible, leveraging the macOS version of Bash I've tried this method: (sorry, this forum won't allow the link) xcode-select --install sleep 1 osascript <<EOD tell application "System Events" tell process "Install Command Line Developer Tools" keystroke return click button "Agree" of window "License Agreement" end tell end tell EOD This automation fails because on first-run, the Security & Privacy wants (user) approval for: Accessibility > sshd-keygen-wrapper: annoying (bottom) This approval must be provided before the install but there is no way to manually approve before the install, nor automate the approval during the install At least not as far as far as I can see. Any help is appreciated. TIA
Posted
by voidsurfr.
Last updated
.
Post not yet marked as solved
1 Replies
273 Views
Trying to automated running this shell script and getting the results. So I have a shell script: backup.sh -- finds latest backup time machine backup date, creates a file on the desktop called bkDate.txt then added the date into the file. #!/bin/sh enabled=`/usr/bin/defaults read /Library/Preferences/com.apple.TimeMachine AutoBackup` if [ "$enabled" == "1" ];then lastBackupTimestamp=`date -j -f "%a %b %d %T %Z %Y" "$(/usr/libexec/PlistBuddy -c "Print Destinations:0:SnapshotDates" /Library/Preferences/com.apple.TimeMachine.plist | tail -n 2 | head -n 1 | awk '{$1=$1};1')" "+%Y-%m-%d %H:%M:%S"` echo "$lastBackupTimestamp" else echo "<result>Disabled</result>" fi echo "$lastBackupTimestamp" > ~/Desktop/bkDate.txt If I run it manually through sh ~/Desktop/backup.sh it works if I use automator (shell or AppleScript) or crontab. It produces the file but the contents is empty. Trying to figure out why it's not letting me automate it and how would can I automate the file and output?
Posted
by syphon.
Last updated
.
Post not yet marked as solved
3 Replies
320 Views
Trying to figure out if this is even possible- here's what I'd love to be able to do: Start script Send message "X" via TCP/UDP OR HTTP OR OSC if system audio input is muted, send message "Y" if unmuted. Continue to watch and send a new message when the mic is muted or unmuted until the script stopped. Not sure if this is even possible- any suggestions on proper nomenclature to start my research would be most appreciated!
Posted
by SClute.
Last updated
.
Post not yet marked as solved
2 Replies
1.1k Views
I have simple script to turn down the brightness of my MacBook Pro via an AppleScript. This worked fine in BigSur, but has stopped working after I upgraded to Monterey 12.0.1. The script is as follows: tell application "System Preferences" reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays" end tell tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display" set value of value indicator 1 of slider 1 of tab group 1 to 0.0 end tell ..error is as follows in script editor: error "System Events got an error: Can’t set window \"Built-in Retina Display\" of process \"System Preferences\" to 0.0." number -10006 from window "Built-in Retina Display" of process "System Preferences" Any suggestions on what to modify to get it working again?
Posted
by Blokie.
Last updated
.
Post not yet marked as solved
2 Replies
537 Views
Until Big Sur I was asking the administrative privileges using the command /usr/bin/osascript -e 'do shell script "ls" with prompt "Installer is trying to setup" with administrator privileges' which gives me this dialog box Now the same command in mac os monetery is giving me the prompt with the title as "osascript". How can I replace the osascript title with my app name. Thanks in advance
Posted
by Divyeshm7.
Last updated
.
Post not yet marked as solved
2 Replies
558 Views
I have a Java program that I run in Eclipse which executes AppleScript for certain tasks. It works fine in Mojave, but in Big Sur, the AppleScripts fail with the error "AppleScript Not authorized to send Apple events to [app] (-1743)" In Mojave, the user is prompted (one time on the first run) with "'Eclipse.app' wants access to control '[app being controlled by Applescript]'" Once this prompt is approved, then Eclipse is added in the System Preferences under Security & Privacy -> Privacy -> Automation and a checkbox is included and activate for each of the applications that the AppleScript manipulates (Finder and iTunes or Music app depending on OS version), and thereafter,  my Java program can run its AppleScripts. In Big Sur, the prompts never appear and the AppleScript immediately errors out. Furthermore, I see no way to manually add approvals under System Preferences -> Security & Privacy -> Privacy -> Automation and there is no way I can find for how I can approve this automation on my own Mac. How do I invoke AppleScript on Big Sur from other languages such as Java? Please note that the Java program constructs AppleScript content at run time dependent on data, so the scripts are not fixed.  The Java code to run a script goes like this....   String script = <Some expression to form the content of the script depending on data>; String[] myargs = { "osascript", "-e", script}; try {     Process process = runtime.exec(myargs);     process.waitFor(); // Wait for the script to complete.     if (process.exitValue() == 0) { // Success       //On Mojave, execution takes this path and //Applescript works, after the one time user //approval.         System.out.println("success");     } else { // Fail         //On Big Sur, executions takes this path and //outputs         //35:57: execution error: Not authorized to send //Apple events to Finder. (-1743)         InputStream is = process.getErrorStream();       final BufferedReader reader = new BufferedReader(new InputStreamReader(is));         String line = null;         while ((line = reader.readLine()) != null) {             System.out.println(line);         }         reader.close();     } } catch (Exception exc) {     System.out.println(exc.getMessage());    } Thanks in advance for any help!
Posted
by tk_coder.
Last updated
.