Automate updating attachment names (but keeping the same image) with text from other fields in the record

I am trying to automatically update over 1,500 attachment names in fields within an attachment field where I only have a single image. Relevant to this post:

My table name is: “Books”
The attachment field (that I want to update the file names in) is: {Cover}
Single line text field: {Title}
Link to another record field, with multiple select options: {Author(s)}

Currently, each of the {Cover} file names are completely random and inconsistent. I want to incorporate the {Title} and {Author(s)} text into the new name of the {Cover} attachments, but keep the existing image from the {Cover} and not simply replace it.

The NEW name for the {Cover} attachments would be: “{Title} by {Author(s)} - MySiteName”

If there are multiple authors, ideally, it would have an “and” between their names, but if this is too difficult, the {Title} alone is more than enough to make me satisfied. I have my automation set to “Update record when {Cover} is not empty”, but I can’t figure out the script for the life of me.

I’ve read a couple other community posts about this, but am new to scripting and can’t figure it out based on the other examples provided. Can anybody help me create this script?

Thank you in advance!

Hi @Jonathan_Cottrell, give this a try:

let nameOfTable = "Books"
let nameOfAttachmentField = "Cover"
let nameOfAuthorsField = "Author(s)"
let nameOfTitleField = "Title"

let table = base.getTable(nameOfTable)
let recordQuery = await table.selectRecordsAsync()

for (let record of recordQuery.records) {
    let attachmentField = await record.getCellValue(nameOfAttachmentField)

    if (attachmentField) {
        let title = await record.getCellValueAsString(nameOfTitleField)
        let authors = await record.getCellValue(nameOfAuthorsField)
        if (authors) {
            authors = authors.map(author => author.name)
            authors = authors.join(" and ")
        } else {
            authors = ""
        }

        let newTitle = `${title} by ${authors} - MySiteName`

        await table.updateRecordAsync(record, {
            [nameOfAttachmentField]: [
                { url: attachmentField[0].url, filename: newTitle }
            ]
        })

    }
}