I used the sample template in the below link to create a VM with a custom script extension:
https://github.com/Azure/azure-quickstart-templates/tree/master/201-vm-custom-script-windows
If I stop and start the VM from the azure portal then the custom script extension runs on startup. But if I restart the VM from within the VM (by selecting Restart from the Start menu) the custom script extension does not run. Why wouldn't the custom script extension run when the VM is restarted from within the VM? Are custom script extensions only executed when a VM is started from a deallocated state?
When working with VM scale sets if I deallocate and then start a single VM in the scale set from the Azure portal the custom script extension for that VM does not execute. But if I deallocate and then start the entire scale set from the Azure portal the custom script extension does execute for each VM.
The Azure custom script extension allow the owner of the Azure VM to run script stored in Azure storage during or after VM provisioning. The script extension only executes once per VM, not every time the machine boots up - but if you stop the VM via Azure portal, and start the VM again, the VM will be re-provisioned, so the script will run again. Difference between the states of Azure Virtual machines stopped and stopped(deallocated), refer to the link.
If you need to run scripts repeatly, you can add a timestamp parameter to your custom script extension, more information refer to the link.