Been doing a lot of SFDX lately and in automating the deployment, testing, and validation of unlocked packages I have found that the documentation around sfdx force:apex:execute is a bit lacking. There are a couple things that got missed in the documentation that you need to know to get this working:
- The file format is just like what you would type in to anonymous console except that you cannot call other methods and classes, it seems everything needs to reside in the script file. If you are using this script to create data and already have a nice test factory going…you will have to move all that code over to the script file.
- You can store this script anywhere but the proper ‘salesforce’ spot for storing these files is the ./scripts/apex folder. If you do a ‘sfdx force:project:create –projectname ProjectName’ it will create that folder with the standard folder structure for you with a couple example. I mention this only because these folders will not get created if you just create a project under VS Code.
Here’s the command I use:
sfdx force:apex:execute –loglevel debug -u scratch_Org_Name -f ./scripts/apex/install.apex
And the official documentation URL: https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_apex.htm#cli_reference_execute