Using SFDX to execute apex against a scratch org

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:

  1. 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.
  2. 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:

Leave a Reply

Your email address will not be published. Required fields are marked *