function main() {
/***
This script will auto-pause campaigns when the account exceeds its monthly budget.
No more daily monitoring of account budgets!
***/
Logger.log("**********************");
Logger.log("Running BUDGET - Pause Performance Max Campaigns script...");
Logger.log("**********************");
// THIS AMOUNT WILL VARY CLIENT BY CLIENT
// MAKE SURE IT IS CORRECT
var monthlyBudget = 500;
var pmaxTotalCost = 0;
var campaignList = [];
var pmaxCampaignIterator = AdsApp.performanceMaxCampaigns().get();
while (pmaxCampaignIterator.hasNext()) {
var pmaxCampaign = pmaxCampaignIterator.next();
// Save each current campaign into an array for ease of iteration
campaignList.push(pmaxCampaign);
// Use THIS_MONTH to get data for all days in the current month
var stats = pmaxCampaign.getStatsFor('THIS_MONTH');
var pmaxCampaignCost = stats.getCost();
Logger.log("PMAX Campaign: " + pmaxCampaign.getName() + " | Cost: " + pmaxCampaignCost);
pmaxTotalCost += pmaxCampaignCost;
}
Logger.log("**********************");
Logger.log("Performance max campaigns total cost for this month: " + pmaxTotalCost);
Logger.log("**********************");
// Search Campaigns
Logger.log("**********************");
Logger.log("Running BUDGET - Pause Search Campaigns script...");
Logger.log("**********************");
var cmpTotalCost = 0;
var campaignIterator = AdsApp.campaigns().get();
while (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
// Save each current campaign into an array for ease of iteration
campaignList.push(campaign);
// Use THIS_MONTH to get data for all days in the current month
var stats = campaign.getStatsFor('THIS_MONTH');
var campaignCost = stats.getCost();
Logger.log("Campaign: " + campaign.getName() + " | Cost: " + campaignCost);
cmpTotalCost += campaignCost;
}
Logger.log("Campaigns total cost for this month: " + cmpTotalCost);
var totalCost = cmpTotalCost + pmaxTotalCost;
Logger.log("**********************");
Logger.log("All Campaign's total cost: " + totalCost);
Logger.log("**********************");
// If totalCost of combined campaigns exceeds defined monthlyBudget, pause all!
if (totalCost > monthlyBudget){
Logger.log("Monthly budget met or exceeded. Auto-pausing all campaigns!");
for (var i = 0; i < campaignList.length; i++) {
var campaigns = campaignList[i];
Logger.log("Pausing campaign: " + campaigns.getName());
campaigns.pause();
}
} else {
Logger.log("**********************");
Logger.log("Total monthly cost currently under budget.");
Logger.log("Monthly Cost: " + totalCost);
Logger.log("Monthly Budget: " + monthlyBudget);
Logger.log("**********************");
}
}