I'm writing an AppleScript that will save the number of times it has ever ran to a .txt file on my desktop. It is working great so far, except it won't overwrite the old data. Here is my code:
property numberOfUnitTests : 0
set numberOfUnitTests to numberOfUnitTests + 1
display dialog "Number of unit tests ran to date: " & numberOfUnitTests & ""
set the logFile to ((path to desktop) as text) & "log.txt"
set the logText to "Number of unit tests ran to date: " & numberOfUnitTests & ""
try
open for access file the logFile with write permission
write ((logText) & return) to file the logFile starting at eof
close access file the logFile
on error
try
close access file the logFile
end try
end try
Now, this never over writes it. It just adds to the end of the file on a new line. I've tried adding in set eof logFile to 0, but then just nothing will save.
You are appending to the file:
starting at eof
by starting at the End Of File, not at the beginning...
property numberOfTimesRan : 0
set numberOfTimesRan to numberOfTimesRan + 1
display dialog "Number of tests ran to date: " & numberOfTimesRan & ""
set the logFile to ((path to desktop) as text) & "test.txt"
set the logText to numberOfTimesRan
try
open for access file the logFile with write permission
write ((logText as string) & return) to file the logFile --- starting at eof
close access file the logFile
on error
try
close access file the logFile
end try
end try
Also you were need to coerce the data to be a string
I would do it like this...
property numberOfTimesRan : 0
set numberOfTimesRan to numberOfTimesRan + 1
display dialog "Number of tests ran to date: " & numberOfTimesRan
set the logFile to POSIX path of (path to desktop as text) & "test.txt"
do shell script "echo " & numberOfTimesRan & " > " & quoted form of logFile
Related
I just updated to Catalina and one of my applescripts no longer works. Wondering if anyone has any ideas as to why? All of the folders selected (single or batch) are on a work server.
The result I get from the Script Editor after selecting a folder is:
-- 'ascr''err '{ '----':'utxt'("Can’t make Can’t make some object
into type some object."), 'errn':-1700,
'erob':'alis'("file:///System/Volumes/Data/data/ARLSCAN2/DIGI/ORIG/FRETSCHEL/Auto/DONE/F2509")
}
--Script Name:
set ScriptName to "jhoveValidation"
--Define user name
set userName to do shell script "whoami"
--Initalize ErrorCount
set errorCount to 0
--Initalize stampCount
set stampCount to 0
-- BEGIN SCRIPT!
--Option to change location mode
set locationModeChoice to display dialog "Would you like to check a single box folder or batch check a directory of box folders?" buttons ["Exit", "Single", "Batch"] default button 3 with title ScriptName with icon caution
set locationModeChoice to button returned of locationModeChoice
if locationModeChoice = "Exit" then
return
end if
if locationModeChoice = "Single" then
set imageDirectory to choose folder with prompt "Select Single Box Folder"
else if locationModeChoice = "Batch" then
set customFolder to choose folder with prompt "Please select a folder of box folders with standard ICT hierarchy:"
set masterFolder to customFolder
end if
-- BEGIN PREFLIGHT
--Populates list of files in finder
set progress description to "jhoveValidation"
set progress additional description to "Loading box and file information..."
set progress total steps to -1
delay 1
if locationModeChoice = "Batch" then
tell application "Finder"
set masterList to folders in masterFolder
if (count of items in masterList) is 0 then
display dialog "ERROR: No files were detected" buttons ["Quit"]
return
end if
end tell
else if locationModeChoice = "Single" then
set masterList to {}
set masterList to masterList & imageDirectory
end if
-- BEGIN IMAGE PROCESSING
set folderCount to count masterList
set folderCounter to 1
repeat with aFolder in masterList
set currentWorkingBox to getLastPathItem(aFolder)
tell application "Finder"
try
set inputFolder to (every folder in aFolder whose name begins with "TIFF") as alias
on error
display dialog "There was an error finding your TIFF folder for box:
" & currentWorkingBox & "
Please place the images you want to inspect in a completed box folder with a TIFF folder inside." buttons ["Quit"]
return
end try
end tell
set progress description to (currentWorkingBox as text) & ": jhoveValidation - Box " & folderCounter & " of " & folderCount
set progress additional description to "Loading TIFF files..."
set progress total steps to -1
tell application "Finder"
try
set filesList to files in inputFolder
set filesCount to count filesList
on error
display dialog "There was an error finding your TIFF folder for box:
" & currentWorkingBox & "
Please place the images you want to inspect in a completed box folder with a TIFF folder inside." buttons ["Quit"]
return
end try
end tell
--***BEGIN LOOP***
--Individual file processing begins here
set loggingCounter to 0
set totalSteps to count filesList
set progress total steps to totalSteps
repeat with aFile in filesList
set loggingCounter to loggingCounter + 1
log loggingCounter
set progress additional description to "Processing file " & loggingCounter & " of " & totalSteps
set progress completed steps to loggingCounter
set AppleScript's text item delimiters to "."
if (the last text item of (aFile as text) is "tif") then
tell application "Finder"
set theFile to aFile as alias
set theFilePath to POSIX path of theFile
log theFilePath
end tell
do shell script "cd ~/Desktop/jhove; ./jhove -c conf/jhove.conf -l SEVERE -o " & (theFilePath as text) & ".txt -m TIFF-hul " & theFilePath
else
end if
end repeat
set progress additional description to "Processing Results & Generating Reports..."
set progress total steps to -1
set currentWorkingFolderPath to POSIX path of (aFolder as alias)
try
do shell script "mkdir " & currentWorkingFolderPath & "VALIDATION"
end try
do shell script "mv " & currentWorkingFolderPath & "TIFF/*.txt " & currentWorkingFolderPath & "VALIDATION"
do shell script "grep -H 'Status' " & currentWorkingFolderPath & "VALIDATION/*.txt | sed 's/:/,/' > " & currentWorkingFolderPath & "VALIDATION/results.csv"
set theResults to {}
set theResults to theResults & paragraphs of (do shell script "cat " & currentWorkingFolderPath & "VALIDATION/results.csv")
set resultsCount to count theResults
set rejectList to {}
set reportStatus to "PASS"
set passCounter to 0
set failCounter to 0
repeat with aResult in theResults
set AppleScript's text item delimiters to ","
log text item 2 of aResult
set thisVar to text item 2 of aResult
if (text item 2 of aResult as text) = " Status: Well-Formed and valid" then
set passCounter to passCounter + 1
log "PASS"
else
set failCounter to failCounter + 1
set rejectList to rejectList & aResult
set reportStatus to "FAIL"
log "FAIL"
end if
end repeat
set totalCount to passCounter + failCounter
if reportStatus = "PASS" then
do shell script "echo \"All files have passed JHOVE Validation.\" > " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \" \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"" & passCounter & " files were validated.\" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \" \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "date >> " & currentWorkingFolderPath & "jhoveReport.txt"
else
do shell script "echo \"!!! ATTENTION - some files have failed JHOVE Validation!!! \" > " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"" & passCounter & " files passed.\" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"" & failCounter & " files failed.\" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \" \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"----- \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"The following have reported failed JHOVE Validation: \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
repeat with aReject in rejectList
do shell script "echo \"" & aReject & "\" >> " & currentWorkingFolderPath & "jhoveReport.txt"
end repeat
do shell script "echo \" \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "echo \"----- \" >> " & currentWorkingFolderPath & "jhoveReport.txt"
do shell script "date >> " & currentWorkingFolderPath & "jhoveReport.txt"
end if
set folderCounter to folderCounter + 1
end repeat
--***END LOOP***
-- END SCRIPT
-- Function: Returns the document name without extension (if present)
on getBaseName(fName)
set baseName to fName
repeat with idx from 1 to (length of fName)
if (item idx of fName = ".") then
set baseName to (items 1 thru (idx - 1) of fName) as string
end if
end repeat
return baseName
end getBaseName
on getLastPathItem(thePathToParse)
set thePathToParse to (thePathToParse as text)
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to ":"
set lastPathLength to the number of text items in thePathToParse
set lastPathTarget to lastPathLength - 1
set the lastPathItemItem to text item lastPathTarget of thePathToParse
set AppleScript's text item delimiters to oldDelims
return lastPathItemItem
end getLastPathItem
on getLastPathItemFile(thePathToParse)
set thePathToParse to (thePathToParse as text)
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to ":"
set the lastPathItemItem to the last text item of thePathToParse
set AppleScript's text item delimiters to oldDelims
return lastPathItemItem
end getLastPathItemFile
am trying to capture screenshot and dump into folder on the desktop with the applescript..
i was successful in taking the screenshot but not dumping into folder which is not existing on the desktop.. Pls suggest..
I tried..
set loc to "/Users/username/Desktop/New Folder"
property N : 0
set N to N + 1
set picPath to (loc & "Picture_" & N & ".png") as string
do shell script "screencapture -tjpg " & quoted form of picPath
After the first line (set loc...) add the following line:
do shell script "mkdir -p " & quoted form of loc
I am using VBS to
Upload a file to FTP
Verify the upload process
I am using the method which creates a text file, fills it with the appropriate command and then execute it using ftp.exe in windows.
FTPCommand = "%systemroot%\System32\ftp.exe -s:session.txt"
FTPCommand = objshell.ExpandEnvironmentStrings(FTPCommand)
objshell.Run FTPCommand,, vbTrue
fso.DeleteFile "session.txt", vbTrue
Part 1 is done using this code:
Set SessionFile = fso.OpenTextFile("session.txt", 2, vbTrue)
With SessionFile
.WriteLine "open abcd.com"
.WriteLine "username"
.WriteLine "pwd"
.WriteLine "cd /Test/Test1"
.WriteLine "put """ & File.Path & """"
.WriteLine "quit"
.Close
End With
FTPCommand = "%systemroot%\System32\ftp.exe -s:session.txt"
FTPCommand = objshell.ExpandEnvironmentStrings(FTPCommand)
objshell.Run FTPCommand,, vbTrue
fso.DeleteFile "session.txt", vbTrue
And Part 2 is done using this code:
Set SessionFile = fso.OpenTextFile("session.txt", 2, vbTrue)
With SessionFile
.WriteLine "open abcd.com"
.WriteLine "username"
.WriteLine "pwd"
.WriteLine "cd /Test/Test1"
.WriteLine "ls"
.WriteLine "close"
.WriteLine "bye"
.Close
End With
FTPCommand = "%systemroot%\System32\ftp.exe -s:session.txt"
FTPCommand = objshell.ExpandEnvironmentStrings(FTPCommand)
set ObjExec=objshell.exec(FTPCommand)
DO WHILE ObjExec.status=0 : wscript.sleep 50 : LOOP
StrTemp=ObjExec.stdout.readall
IF instr(1,StrTemp,File.Name,1)<>0 THEN
AlertMessage = AlertMessage & vbTab & "STATUS: UPLOAD SUCCESSFUL" & vbCrLf & vbCrLf
ELSE
AlertMessage = AlertMessage & vbTab & "STATUS: UPLOAD FAILED" & vbCrLf & vbCrLf
END IF
fso.DeleteFile "session.txt", vbTrue
The problem is that (in part 2 code) the code after
DO WHILE ObjExec.status=0 : wscript.sleep 50 : LOOP
never returns.So the file gets uploaded but the code to check the status never returns.
The session.txt file does not get delete and when I execute the command
%systemroot%\System32\ftp.exe -s:session.txt
manually it indeed shows me the list of files (because of ls command).
I have 3 questions:
Why it does not return. Where to start debugging from?
Is there anyway I can upload the file and check its status(maybe by
the error code returned by the ftp command after the "put" command).
Is there is an incorrect directory specified in the code to upload
file, the cd command fails and it incorrectly "puts" the file in the
root folder. same goes for the code checking the file upload. So
even if the directory specified in wrong, the program returns it as
successful
Edit 1:
I tried it using
.WriteLine "cd /Test"
and it worked. Is that directory switching (two folders deep)causing the problem ?
Edit 2:
I ran the ls command manually and it ran fine. The output is:
226 Transfer complete.
ftp: 586493 bytes received in 4.28Seconds 137.00Kbytes/sec.
Is 586493 bytes too much for this ?
I believe the problem may be:
1)The large no of files returned by LS command.
2)The directory structure I am accessing.
Edit:3
From this microsoft website it looks like the above point 1 is the culprit:
A console application's StdOut and StdErr streams share the same
internal 4KB buffer. In addition, the WshScriptExec object only
provides synchronous read operations on these streams. Synchronous
read operations introduce a dependency between the calling script
reading from these streams and the child process writing to those
streams, which can result in deadlock conditions.
I believe the problem is the way you read the stdout from the process. I use this technique succesfully as follows, sorry, I have no time to adapt your script and try it out, so that is up to you.
The following executes a ping to check if the server is online.
Function IsOnline(Address)
Dim strText
IsOnline = False
Set oExecObj = oShell.Exec("%comspec% /c ping -a -n 1 -w 20 " & Address)
Do While Not oExecObj.StdOut.AtEndOfStream
strText = oExecObj.StdOut.ReadAll()
If Instr(strText, "Reply from") > 0 Then
IsOnline = True
Exit Function
End If
Loop
End Function
In the past I had created an applescript for datedspace but which is not running anymore.
I would like to create an applescript that would look inside a folder ~/Documents/pool/ or ~/Downloads.
Let's say we are on February 7, 2011.
Check if the ~/Documents/2011/02/07/ exists
If not create ~/Documents/2011/02/07/
Move the files and/or folders inside ~/Documents/pool/ to ~/Documents/2011/02/07/
Bonus
Create a text file in ~/Documents/2011/ with the name index.mdown and containing the following format
# Index 2011
## January
[…]
## February
* 2011-02-07: Foo.jpeg
* 2011-02-07: Bar/
Lead or incomplete solutions are welcome.
Previous script
-- Script to automaticaly save documents in a date space.
-- Karl Dubost - http://www.la-grange.net/ - <karl#*******> - 2001 ©
-- Feel free to distribute it and modify it
-- Feel free to send me improvements
-- ********************************************************
-- Version 1.1 2001-03-30
-- Add control on existence of folders year and month
-- Make it more general based on Startup Disk
-- Version 1.0 2001-03-29
-- Creation of the code
-- Thanks to Bill Briggs
-- http://maccentral.macworld.com/columns/briggs.shtml
-- ********************************************************
on adding folder items to this_folder after receiving added_items
tell application "Finder"
set yourDisk to name of startup disk as string
end tell
set todaysDate to (current date)
set {d, m, y} to {day, month, year} of todaysDate
set monthList to {January, February, March, April, May, June, ¬
July, August, September, October, November, December}
repeat with i from 1 to 12
if m = (item i of monthList) then
set monthString to text -2 thru -1 of ("0" & i)
exit repeat
end if
end repeat
set y to y as string
set dayString to text -2 thru -1 of ("0" & d)
set dayString to dayString as string
set datedFolder to yourDisk & ":Documents:" & y & ":" & monthString & ":" & dayString & ":" as string
set monthFolder to yourDisk & ":Documents:" & y & ":" & monthString & ":" as string
set yearFolder to yourDisk & ":Documents:" & y & ":" as string
set rootFolder to yourDisk & ":Documents:" as string
tell application "Finder"
if (folder datedFolder exists) then
repeat with oneFile in added_items
move oneFile to folder datedFolder
end repeat
else if not (folder yearFolder exists) then
make new folder at folder rootFolder with properties {name:y}
else if not (folder monthFolder exists) then
make new folder at folder yearFolder with properties {name:monthString}
else
make new folder at folder monthFolder with properties {name:dayString}
repeat with oneFile in added_items
move oneFile to folder datedFolder
end repeat
end if
end tell
end adding folder items to
I hope this will be good enough :-) :
With the help of some basic command line applications it creates subfolders in your ~/Documents folder (mkdir -p: it will not overwrite existing directories!), moves files there (mv -n: not overwriting files with the same name), then creates monthly logfiles containing the names of addedItems and finally a index.mdown file with all monthly logfiles which should look like this:
2011/01/03: testfile9
2011/02/01: testfile10
2011/02/07: testfile11
Now go ahead and attach it to your folder, give it a try! (maybe uncomment baseFolder and change it to /tmp/test or something, or to POSIX path of thisFolder, if you want it to clean up the folder it´s attached to.)
property dateFormatForFolder : "+%Y/%m/%d"
property dateFormatForMonthlyLog : "+%Y/%m/"
property dateFormatForYearlyLog : "+%Y/"
on adding folder items to thisFolder after receiving addedItems
set baseFolder to POSIX path of (path to documents folder)
set todaysFolder to do shell script "/bin/date '" & dateFormatForFolder & "'"
set monthsFolder to do shell script "/bin/date '" & dateFormatForMonthlyLog & "'"
set yearsFolder to do shell script "/bin/date '" & dateFormatForYearlyLog & "'"
set fullPath to baseFolder & todaysFolder
createFolder(fullPath)
repeat with i from 1 to number of items in addedItems
set oneItemsPath to (quoted form of POSIX path of item i of addedItems)
try
moveToFolder(fullPath, oneItemsPath)
end try
set fileName to name of (info for item i of addedItems)
set logThis to todaysFolder & ": " & fileName
do shell script "echo " & logThis & " >> " & baseFolder & monthsFolder & "log.txt"
end repeat
do shell script "find " & baseFolder & yearsFolder & " -type f -name 'log.txt' -print0 | xargs -0 cat > " & baseFolder & yearsFolder & "index.mdown"
end adding folder items to
on createFolder(fullPath)
do shell script "/bin/mkdir -p " & quoted form of fullPath
end createFolder
on moveToFolder(fullPath, oneItemsPath)
do shell script "/bin/mv -n " & oneItemsPath & " " & fullPath
end moveToFolder
I have a VB script which needs to run psexec to launch an app called md5 on a remote server. Md5 generates a hash key of a file and takes one parameter - the file path\name. I need to retrieve the has key that is generated to store in a variable. Below is the code I am using:
Set objShell = CreateObject("Wscript.Shell")
strcomputer = "remotecomputer"
tempDest = "C:\somedir"
filename = "somefile"
strCommand = "psexec -accepteula \\" & strcomputer & " -c md5.exe " & tempDest & "\" & filename & " > log.txt"
Set objExecObject = objShell.Exec("%comspec% /c " & strCommand)
Do While objExecObject.Status <> 1 'loop until previous process has finished
WScript.Sleep 100
Loop
The MD5 command is run however nothing is written to the log file. When I copy and paste strCommand (substituting all the variables for the actual data) into a cmd prompt and run it, it successfully writes the output of Md5 to the log file.
At the end of the day I just need the output of Md5, if anyone knows a better way than writing it to a log file please let me know. I have already tried using objExecObject.StdOut.Readall() to try and catch the output which resulted in random failures - sometimes it would catch the output, sometimes it wouldn't, without changing anything in the script.
Just a guess: Are you sure about what the current directory is when the script is running? Try giving an absolute path to the log file and see if it helps.
I found a solution for this. Instead of using the following code:
strCommand = "psexec -accepteula \\" & strcomputer & " -c md5.exe " & tempDest & "\" & filename & " > log.txt"
Set objExecObject = objShell.Exec("%comspec% /c " & strCommand)
Do While objExecObject.Status <> 1 'loop until previous process has finished
WScript.Sleep 100
Loop
I used this instead:
strCommand = "psexec -accepteula \\" & strcomputer & " -c md5.exe " & tempDest & "\" & filename & " > log.txt"
objShell.Run "%comspec% /c " & strCommand, 0, true
The script is now redirecting to log.txt properly.