You can do this using Folder Actions:
Ctrl-click any folder in the Finder and choose Services>Folder Actions Setup in Monterey.
In early versions of macOS, the option appears in the main lists of contextual items.
To avoid the malicious and accidental installation of Folder Actions, macOS requires a confirmation step that can’t be automated: click Run Service in the Confirm Service dialog.
This adds the current folder to the Folders with Actions list without adding actions.
The Folder Actions Setup window appears with a dialog already open that reads Choose a Script to Attach.
This list includes ones that Apple seeded, locating them inside the /Library/Scripts/Folder Actions Scripts folder. Any scripts installed by apps or that you’ve created and placed inside your Home directory’s ~/Library/Scripts/Folder Actions Scripts folder appear as well.
You can create Folder Actions in a numbers of ways:
Use an item Apple provides in the dialog that appears when you invoke Folder Actions Setup. These mostly relate to image processing.
Create a Folder Action in Automator using its broader set of tools. This can include passing information to an AppleScript, JavaScript, or shell script.
Write your own AppleScript to perform a task.