Script Failing without error

I’m writing a script that walks through a folder structure and returns the filename and page count of any PDF found, writing that into a text file.

In order to get the page count, I’m using mdls in a do shell script command.

The problem occurs when I’m setting the variable to be written to the text file. The script aborts at that point but without any error.
This is the line: set theText to this_item & tab & (do shell script shellCmd) & return

I’ve run in debug mode in Script Debugger and I’m not seeing anything when I execute that line which would indicate the problem.

A number of people here have contributed to what’s in this script through its predecessors, so there are sections that are much more advanced than my scripting skills might otherwise be…

If you could be so kind as to help me understand why the script is failing, I’d be grateful.

Thanks.

Cheers,
Jon

--
--	Created by: Jonathan Duke
--	Created on: 3/16/21
--
--	Copyright © 2021 Fitch Law Partners LLP, All Rights Reserved
--
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
-- <https://www.macosxautomation.com/applescript/apps/FileManagerLib_stuff.zip>
use scripting additions

property NSPredicate : a reference to NSPredicate of current application
property NSSortDescriptor : a reference to NSSortDescriptor of current application


property kFileList : {}

set kFileList to {}
set shellCmd1 to "mdls -name kMDItemNumberOfPages -raw "
set overwriteExistingContent to false

--Code from EMail move script as an example of how to mix AS variables and shell script sections
--set shellCmd1 to "find "
--set shellCmd2 to " -type f -newermt "
--set shellCmd3 to "-01-01 ! -newermt "
--set shellCmd4 to "-12-31 -exec mv {} "
--set shellCmd5 to " \\;"
--
--set shellCmd to shellCmd1 & sourceDir & shellCmd2 & mailYear & shellCmd3 & mailYear & shellCmd4 & destDir & shellCmd5
--
--do shell script shellCmd with administrator privileges

--mdls -name kMDItemNumberOfPages -raw file.pdf

with timeout of 360 seconds
	try
		
		
		set theRootFolder to choose folder with prompt "Please select directory."
		set theRootFolderPosixPath to POSIX path of theRootFolder
		
		set URLArray to ¬
			objects of theRootFolderPosixPath ¬
				searching subfolders true ¬
				include invisible items false ¬
				include folders true ¬
				include files true ¬
				result type urls array
		
		set PDFPred to NSPredicate's predicateWithFormat:("pathExtension ==[c] 'pdf'")
		URLArray's filterUsingPredicate:PDFPred
		
		set sortDescriptor to NSSortDescriptor's sortDescriptorWithKey:("path") ascending:(true) selector:("localizedStandardCompare:")
		URLArray's sortUsingDescriptors:({sortDescriptor})
		
		set kFileList to URLArray as list
		
		set theNewFilePath to choose file name with prompt "Save the PDF name and page count document as:"
		set theFile to theNewFilePath
		
		
		repeat with i in kFileList
			
			set this_item to i as alias
			
			set shellCmd to shellCmd1 & quoted form of (POSIX path of i)
			
			set theText to this_item & tab & (do shell script shellCmd) & return  --script fails here without any error being posted.
			
			my writeTextToFile(theText, theFile, overwriteExistingContent) -- writeTextToFile(theText, theFile, overwriteExistingContent)
			
			
		end repeat
		
		
		
	end try
	
	
end timeout



-- A sub-routine for writing text to a file:
-- Courtesy of Apple 
-- https://developer.apple.com/library/archive/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/ReadandWriteFiles.html

on writeTextToFile(theText, theFile, overwriteExistingContent)
	try
		
		-- Convert the file to a string
		set theFile to theFile as string
		
		-- Open the file for writing
		set theOpenedFile to open for access file theFile with write permission
		
		-- Clear the file if content should be overwritten
		if overwriteExistingContent is true then set eof of theOpenedFile to 0
		
		-- Write the new content to the file
		write theText to theOpenedFile starting at eof
		
		-- Close the file
		close access theOpenedFile
		
		-- Return a boolean indicating that writing was successful
		return true
		
		-- Handle a write error
	on error
		
		-- Close the file
		try
			close access file theFile
		end try
		
		-- Return a boolean indicating that writing failed
		return false
	end try
end writeTextToFile


Just an update. I figured out the first problem-the initial file in the folder of test file had something funky with its name and would not even work in Terminal.

Now the write fails with the following error:
open for access current application with write permission
Error: unable to coerce the data to the desired type (errAECoercionFail:-1700)
Paused at exception: Can’t make current application into type «class fsrf»

Can you offer suggestions on how to fix this?

Thanks.

Cheers,
Jon

Hi.

That sounds like a known problem: AppleScript ‘file’ specifiers don’t work when you’re using ASObjC in the same script. You have to use a coercion instead. So open for access file theFile with write permission becomes open for access (theFile as «class furl») with write permission.

Generally, if you have a script full of ‘try’ statements which fails without reporting an error, the first thing to try is either to comment out the ‘try’/‘end try’ lines or, perhaps safer here, add an ‘on error’ section which reports what the error is.

Given that you’re using an advanced shell method, it may interest you to learn a simpler way to write to a file; follow the shell command with the greater-than symbol and a destination path. I’ve removed your ASObjC dependency in my example.

do shell script "find " & my (choose folder with prompt "Where are the PDF files for name and length extraction?")'s POSIX path's quoted form & " -name '*.*' -prune -name '*.pdf' -print0 | Xargs -0  mdls -name kMDItemDisplayName -name kMDItemNumberOfPages -name kMDItemAudioBitRate -nullMarker " & linefeed's quoted form & " -raw | sort -h  > " & ((path to desktop folder as text)'s POSIX path & "/newFile.txt")'s quoted form

Nigel,

Thank you. I’ve been writing scripts for a while but this is the first time I need to write output to a file.

I’ve made your suggested change, but am still receiving a -1700 coercion error when trying to open the file for output. I’m running 10.14.6 and all current updates on the development system.

Is there any other change that I should make with regards to specifying the output file?

Thanks.

Cheers,
Jon

Hi Jon.

I’m not really sure what the problem is with opening the file if what I suggested didn’t cure it. :confused:

Looking at the script more closely, I can say that ‘theText’ isn’t text! It’s formed by concatenating things to an alias (‘this_item’), so the result is a list containing the alias and three pieces of text. Mind you, ‘this_item’ will only be an alias if ‘i’ is something that can be coerced to alias. If not, that might be the coercion failure that’s causing the error. It’s hard to tell from the code what’s in ‘kFileList’.