Skip to main content
Inspiring
January 7, 2023
Answered

How to use multiple conditions in Photoshop script

  • January 7, 2023
  • 1 reply
  • 1502 views

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?

This topic has been closed for replies.
Correct answer Stephen Marsh
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

 


@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);
        }
    }
}

 

1 reply

Stephen Marsh
Community Expert
Community Expert
January 7, 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 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.

Inspiring
January 7, 2023

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.

 

Stephen Marsh
Community Expert
Community Expert
January 7, 2023
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.