Skip to main content
Example scripts
arrow icon
To homepage
Confluence
Data centre icon
Data Center

Add a Label to an Attachment on a Page

Created 1 year ago, Updated 1 month(s) ago
App in script
ScriptRunner For Confluence
ScriptRunner For Confluence
by Adaptavist
Compatibility
compatibility bullet
Confluence (7.15 - 8.6)
compatibility bullet
ScriptRunner For Confluence (7.10.0)
Language |
groovy
import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.confluence.pages.AttachmentManager
import com.atlassian.confluence.pages.PageManager
import com.atlassian.confluence.labels.Label
import com.atlassian.confluence.labels.LabelManager

def pageManager = ComponentLocator.getComponent(PageManager)
def attachmentManager = ComponentLocator.getComponent(AttachmentManager)
def labelManager = ComponentLocator.getComponent(LabelManager)

def spaceKey = '<YOUR_SPACE_KEY>'
def pageTitle = '<YOUR_PAGE_TITLE>'
def attachmentName = '<YOUR_ATTACHMENT_NAME>'
def newLabel = '<YOUR_LABEL_TO_ADD>'

//get page
def page = pageManager.getPage(spaceKey, pageTitle)

// return if the page doesn't exist.
if ( !page ) {
    log.warn "Page with title '${pageTitle}' in  space '${spaceKey}' does not exist."
    return
}

//get all attachment in specific page.
def allAttachments = attachmentManager.getLatestVersionsOfAttachments(page)
def label = new Label(newLabel)

allAttachments.each { attachment ->
    if ( attachment.nameForComparison == attachmentName) {
        labelManager.addLabel(attachment, label)
    }
    log.warn "${attachment.nameForComparison} ===> ${attachment.labels}"
}
Having an issue with this script?
Report it here