• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

How to use multiple conditions in Photoshop script

Community Beginner ,
Jan 07, 2023 Jan 07, 2023

Copy link to clipboard

Copied

I have a folder that contains PSD files, XMP files, ARW files and JPG files.

Some of the PSD files have a layer called "Background".

I want to create a script that checks only the PSD files for the layer named "Background", and if it exists, remove it. If it doesn't exist, close the file without saving.

 

So the script needs to check the file-type, and then check for the presence of that named layer. I managed to almost get there with this script but I am not sure if the two conditions (that both need to be true) are correctly defined here:

 

if (app.activeDocument.name.indexOf('.psd') != -1 && app.activeDocument.artLayers.getByName("Background") != -1) {
app.activeDocument.artLayers.getByName("Background").remove();
}
else {app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);}

When I run this script on the folder, it almost works as I want. Non-PSD files get opened and immediately closed. From PSD files that contain the layer, the layer is removed and the file is saved. However, PSD files that did not contain the "Background" layer to begin with, they should just close immediately. But instead I get an error: "An error was encountered while batching". When I check the log, it just says: "Error: Could not complete the ScriptingSupport command because of a program error. (-1)"

 

How can I fix it so that PSD files that do not have a layer called "Background" are ignored?

TOPICS
Actions and scripting

Views

486

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 2 Correct answers

Community Expert , Jan 07, 2023 Jan 07, 2023

@loco27057486xady – Just curious, are you checking for a "true" Background image layer i.e. .backgroundLayer – or just any "floating" layer named "Background"?

 

Batch was designed for actions. Although you can record the execution of a script into an action and batch it, perhaps the error is being triggered when in the batch but not otherwise? What happens if you just run the script on a single file without a Background layer?

 

You could see if a try/catch block suppresses the error when batch

...

Votes

Translate

Translate
Community Expert , Jan 07, 2023 Jan 07, 2023

@loco27057486xady – Here is an example of a batch script for your workflow, without needing to use a Batch Action:

 

/*
https://community.adobe.com/t5/photoshop-ecosystem-discussions/how-to-use-multiple-conditions-in-photoshop-script/m-p/13472152
v1.0, 8th January 2023, Stephen Marsh
*/

#target photoshop

// Disable dialog display
var restoreDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.NO;

(function () {

    // Select the input directory
    var inputFolder = Folder.selec
...

Votes

Translate

Translate
Adobe
Community Expert ,
Jan 07, 2023 Jan 07, 2023

Copy link to clipboard

Copied

@loco27057486xady – Just curious, are you checking for a "true" Background image layer i.e. .backgroundLayer – or just any "floating" layer named "Background"?

 

Batch was designed for actions. Although you can record the execution of a script into an action and batch it, perhaps the error is being triggered when in the batch but not otherwise? What happens if you just run the script on a single file without a Background layer?

 

You could see if a try/catch block suppresses the error when batching:

 

try {
    if (app.activeDocument.name.indexOf('.psd') != -1 && app.activeDocument.artLayers.getByName("Background") != -1) {
    app.activeDocument.artLayers.getByName("Background").remove();
} else {
    app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
} catch (error) {}


I'd personally do the batching directly in the script, with a file type filter so that only PSD files are opened from the nominated input folder.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Jan 07, 2023 Jan 07, 2023

Copy link to clipboard

Copied

Thanks Stephen for the reply, it helped me get the problem fixed 🙂 I added a try/catch as you suggested, and now it works as intended. In fact, now that I look at your example I see my solution is exactly the same code 🙂

 

For reference, I am indeed trying to remove true background layers from PSD files. If you know of a better code for this than just a check on "Background" in the layer name, I'm all ears 🙂

 

What do you mean by "batching in the script?" The only reason I use the batch function in Photoshop is indeed to call the script, so that I can run it on an entire folder, rather than individual images.

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 07, 2023 Jan 07, 2023

Copy link to clipboard

Copied

quote

Thanks Stephen for the reply, it helped me get the problem fixed 🙂 I added a try/catch as you suggested, and now it works as intended. In fact, now that I look at your example I see my solution is exactly the same code 🙂

 

By @loco27057486xady

 

Yes, simply wrapping the code in a try/catch without alerting the error in the catch block is a common way to ignore errors in a batch. I didn't want to alter your code so that you could just see how the try/catch worked. I just wasn't sure if it would work as intended while being called from the Batch command.

 

Please mark my reply as the correct solution if it solved your problem.

 

Time permitting, I'll provide some example code for your other questions.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 07, 2023 Jan 07, 2023

Copy link to clipboard

Copied

quote

For reference, I am indeed trying to remove true background layers from PSD files. If you know of a better code for this than just a check on "Background" in the layer name, I'm all ears 🙂


By @loco27057486xady

 

I hinted this above with .backgroundLayer and depending on the context there is also .isBackgroundLayer which you can look into the docs or searching the forum or web for code usage examples.

 

https://theiviaxx.github.io/photoshop-docs/Photoshop/ArtLayer.html?highlight=isbackgroundlayer

 

https://theiviaxx.github.io/photoshop-docs/Photoshop/ArtLayer/isBackgroundLayer.html?highlight=isbac...

 

https://theiviaxx.github.io/photoshop-docs/Photoshop/Document.html?highlight=backgroundlayer

 

https://theiviaxx.github.io/photoshop-docs/Photoshop/Document/backgroundLayer.html?highlight=backgro...

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 07, 2023 Jan 07, 2023

Copy link to clipboard

Copied

@loco27057486xady – Here is a working example of checking for a true .backgroundLayer and removing the .backgroundLayer

 

try {
    if (activeDocument.name.match(/\.psd$/i) && activeDocument.backgroundLayer) {
            activeDocument.backgroundLayer.remove();
    } else {
        app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
    }
} catch (error) {}

 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 07, 2023 Jan 07, 2023

Copy link to clipboard

Copied

quote

What do you mean by "batching in the script?" The only reason I use the batch function in Photoshop is indeed to call the script, so that I can run it on an entire folder, rather than individual images.

 


By @loco27057486xady

 

Recording the script into an action and running batch is pretty quick and easy, I have done it myself many times.

 

It is also possible to create a self-contained script that will batch process, without using an action or the batch command. One advantage is that you can filter on file type, so that only PSD files are opened. This speeds up the batch as you don't need to open a JPG file to check that the document extension is a PSD. Filtering the input file types before opening the file is quicker than opening and then checking the file type.

 

An example snippet here (not full code for your task, just the batch opening bit). You would add or remove file type extensions as required, in your case removing all extensions except for PSD:

 

https://gist.github.com/MarshySwamp/0cd2bcbff88297f2f122a54f6d87e0d5

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Jan 07, 2023 Jan 07, 2023

Copy link to clipboard

Copied

Thanks for the wealth of information Stephen, I will look into it and see if I can optimize my script.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 07, 2023 Jan 07, 2023

Copy link to clipboard

Copied

@loco27057486xady – Here is an example of a batch script for your workflow, without needing to use a Batch Action:

 

/*
https://community.adobe.com/t5/photoshop-ecosystem-discussions/how-to-use-multiple-conditions-in-photoshop-script/m-p/13472152
v1.0, 8th January 2023, Stephen Marsh
*/

#target photoshop

// Disable dialog display
var restoreDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.NO;

(function () {

    // Select the input directory
    var inputFolder = Folder.selectDialog("Please select the input folder:");
    if (inputFolder === null) {
        // alert('Script cancelled!');
        return;
    }

    // Get the Photoshop files
    var fileList = inputFolder.getFiles(/\.psd$/i);

    // Validate that the file list is not empty
    var inputCount = fileList.length;
    var folderSelection = (inputCount === 0);
    if (folderSelection === true) {
        inputFolder = Folder.selectDialog("No files found, please reselect the input folder:");
        return;
    }

    // Start the file count saving counter at zero
    var counter = 0;

    // Loop over the input files
    while (fileList.length) {
        for (var a = 0; a < 1; a++) {
            try {
                app.open(fileList.pop());
            } catch (e) {}
        }
        try {
            if (activeDocument.backgroundLayer) {
                activeDocument.backgroundLayer.remove();
                activeDocument.close(SaveOptions.SAVECHANGES);
                // Increment the file count saving counter
                counter++;
            } else {
                app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
            }
        } catch (error) {}
    }

    // End of script notification
    app.beep();
    alert('Script completed!' + '\r' + counter + ' files updated!');

    // Restore the dialog display
    app.displayDialogs = restoreDialogMode;

}());

 

And here is a different batch version, stripped down without all of the options in the previous script:

 

/*
https://community.adobe.com/t5/photoshop-ecosystem-discussions/how-to-use-multiple-conditions-in-photoshop-script/m-p/13472152
v1.1, 8th January 2023, Stephen Marsh
*/

#target photoshop

var inputFolder = Folder.selectDialog("Select the folder containing PSD files", "~/Desktop");
var inputFiles = inputFolder.getFiles(/\.psd$/i);

for (var i = 0; i < inputFiles.length; i++) {
    try {
        open(inputFiles[i]);
        if (activeDocument.backgroundLayer) {
            activeDocument.backgroundLayer.remove();
            activeDocument.close(SaveOptions.SAVECHANGES);
        }
    } catch (e) {
        while (app.documents.length > 0) {
            app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
        }
    }
}

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Jan 08, 2023 Jan 08, 2023

Copy link to clipboard

Copied

Wow! I just ran your extended version of the script and it works perfectly. Thank you so much for the work you have put into this, I really appreciate it 🙂 Your script will reduce most of my PSD files by at least 33%, which translates to many gigabytes of hard drive space becoming available to me again.

 

Thanks again Stephen!

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jan 08, 2023 Jan 08, 2023

Copy link to clipboard

Copied

LATEST

@loco27057486xady – You're welcome!

 

Depending on the volume of images that you need to process, it is also possible to use the command line ExifTool program to search through the layer metadata of PSD files and flag any files that use a layer name of "Background". This is very fast compared to opening files in Photoshop.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines