Last updated: November 2026
Google Ads scripts are short pieces of JavaScript that run inside your Google Ads account on a schedule, reading your data and sending alerts, writing reports to Google Sheets or making changes that would take hours by hand. This guide has 12 scripts with the full code for each one, ready to paste into your account, covering Quality Score, broken landing pages, wasted search terms, budget pacing, unusual days, disapprovals, Performance Max channels, products that do not sell and ad copy.
Eleven of the twelve only read data and report back to you, and the twelfth adds a label, so none of them pause, bid or spend anything on their own. Every query in them was run against a live ecommerce account in November 2026 before publishing.
Why scripts are still worth running alongside Smart Bidding
Smart Bidding and Performance Max now make most of the bid and placement decisions, which means the work that is left for a person is checking that the automation has good inputs and catching the problems it will not tell you about. A bid strategy can keep spending on a landing page that has started returning a 404 until Google's own checks disapprove the ad, and it cannot tell a conversion tag that stopped firing on Tuesday from a run of bad days. Scripts are a cheap way to watch for those things every day, across every campaign, without anyone having to log in and look.
If you manage more than one account, the same scripts can be adapted to run from a manager account, but the versions below are written for a single account because that is where most people start.
How to add a script to your Google Ads account
- In Google Ads, open Tools, then Bulk actions, then Scripts.
- Click the plus button and choose New script.
- Delete the sample code in the editor, paste in the script, and give it a name you will recognise.
- Change the settings in the
CONFIGblock at the top, such as your email address or Google Sheet URL. - Click Authorise and allow access with the Google account you use for Google Ads.
- Click Preview and read the log at the bottom of the screen to check it ran without errors.
- Save it, then set the frequency from the Scripts list, for example daily at 7am.
For the scripts that write to a Google Sheet, create a blank sheet with the same Google account first and copy its URL from the address bar. Money thresholds in each script are in your account currency, and the scripts work out dates in your account's own time zone.
1. Low Quality Score alert
This script finds enabled keywords with a Quality Score of 4 or lower that have spent at least 10 in your account currency in the last 30 days, adds a Low QS label to them, and emails you the list with the highest spenders first. It deliberately does not pause anything, because a keyword with a poor score can still be your best converter, and that is a decision you want to make with the numbers in front of you.
Not sure where to start?
We help businesses build marketing systems that actually work. Let us show you how.
Get Your Free Growth Plan →Schedule it weekly. Change EMAIL to your address, and raise MAX_QS to 6 if you want an earlier warning on keywords that are slipping.
// Low Quality Score alert
// Labels keywords at or below a Quality Score threshold that have spent money
// in the last 30 days, then emails you the list. It does not pause anything.
const CONFIG = {
EMAIL: '[email protected]',
MAX_QS: 4, // flag keywords with a Quality Score of this or lower
MIN_COST: 10, // only flag keywords that spent at least this much (account currency)
LABEL: 'Low QS'
};
function main() {
const query =
'SELECT campaign.name, ad_group.id, ad_group.name, ad_group_criterion.criterion_id, ' +
'ad_group_criterion.keyword.text, ad_group_criterion.quality_info.quality_score, ' +
'metrics.cost_micros, metrics.conversions ' +
'FROM keyword_view ' +
"WHERE campaign.status = 'ENABLED' AND ad_group.status = 'ENABLED' " +
"AND ad_group_criterion.status = 'ENABLED' " +
'AND ad_group_criterion.quality_info.quality_score <= ' + CONFIG.MAX_QS + ' ' +
'AND segments.date DURING LAST_30_DAYS';
const rows = AdsApp.search(query);
const flagged = [];
const ids = [];
while (rows.hasNext()) {
const row = rows.next();
const cost = Number(row.metrics.costMicros) / 1e6;
if (cost < CONFIG.MIN_COST) continue;
flagged.push({
campaign: row.campaign.name,
adGroup: row.adGroup.name,
keyword: row.adGroupCriterion.keyword.text,
qs: row.adGroupCriterion.qualityInfo.qualityScore,
cost: cost,
conversions: Number(row.metrics.conversions)
});
ids.push([Number(row.adGroup.id), Number(row.adGroupCriterion.criterionId)]);
}
if (flagged.length === 0) {
Logger.log('No keywords at or below QS ' + CONFIG.MAX_QS + ' with spend over ' + CONFIG.MIN_COST);
return;
}
const existing = AdsApp.labels().withCondition("label.name = '" + CONFIG.LABEL + "'").get();
if (!existing.hasNext()) AdsApp.createLabel(CONFIG.LABEL);
const keywords = AdsApp.keywords().withIds(ids).get();
while (keywords.hasNext()) keywords.next().applyLabel(CONFIG.LABEL);
flagged.sort((a, b) => b.cost - a.cost);
const lines = flagged.map(k =>
'QS ' + k.qs + ' | ' + k.keyword + ' | ' + k.campaign + ' > ' + k.adGroup +
' | cost ' + k.cost.toFixed(2) + ' | conv ' + k.conversions.toFixed(1));
MailApp.sendEmail(
CONFIG.EMAIL,
AdsApp.currentAccount().getName() + ': ' + flagged.length + ' keywords at QS ' + CONFIG.MAX_QS + ' or below',
'Labelled "' + CONFIG.LABEL + '". Last 30 days, highest spend first:\n\n' + lines.join('\n'));
}
When the email arrives, filter the keywords view by the label and look at the three components side by side. A below average landing page experience points at the page, below average ad relevance usually means the keyword sits in an ad group whose ads do not mention it, and below average expected CTR is often a sign the keyword is too broad for the ad group it is in.
2. Quality Score history tracker
Google Ads does have historical Quality Score columns, but they give one score for the date range you choose, which makes it hard to see whether a score of 5 used to be an 8 before the landing page changed. This script writes a snapshot of every enabled keyword's score, plus expected CTR, ad relevance and landing page experience, to a Google Sheet each time it runs.
Schedule it daily. Create a blank Google Sheet with the same Google account you use for Google Ads and paste its URL into SHEET_URL. Keywords that do not have enough traffic for a score yet are skipped.
// Quality Score history tracker
// Google only shows today's Quality Score. This writes a daily snapshot of every
// enabled keyword's score and its three components to a Google Sheet.
const CONFIG = {
SHEET_URL: 'https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit',
TAB: 'QS history'
};
function main() {
const tz = AdsApp.currentAccount().getTimeZone();
const today = Utilities.formatDate(new Date(), tz, 'yyyy-MM-dd');
const query =
'SELECT campaign.name, ad_group.name, ad_group_criterion.keyword.text, ' +
'ad_group_criterion.keyword.match_type, ad_group_criterion.quality_info.quality_score, ' +
'ad_group_criterion.quality_info.search_predicted_ctr, ' +
'ad_group_criterion.quality_info.creative_quality_score, ' +
'ad_group_criterion.quality_info.post_click_quality_score ' +
'FROM keyword_view ' +
"WHERE campaign.status = 'ENABLED' AND ad_group.status = 'ENABLED' " +
"AND ad_group_criterion.status = 'ENABLED'";
const rows = AdsApp.search(query);
const out = [];
while (rows.hasNext()) {
const row = rows.next();
const q = row.adGroupCriterion.qualityInfo || {};
if (!q.qualityScore) continue; // keywords without enough data have no score
out.push([
today,
row.campaign.name,
row.adGroup.name,
row.adGroupCriterion.keyword.text,
row.adGroupCriterion.keyword.matchType,
q.qualityScore,
q.searchPredictedCtr || '',
q.creativeQualityScore || '',
q.postClickQualityScore || ''
]);
}
if (out.length === 0) return;
const book = SpreadsheetApp.openByUrl(CONFIG.SHEET_URL);
const sheet = book.getSheetByName(CONFIG.TAB) || book.insertSheet(CONFIG.TAB);
if (sheet.getLastRow() === 0) {
sheet.appendRow(['Date', 'Campaign', 'Ad group', 'Keyword', 'Match type', 'Quality Score',
'Expected CTR', 'Ad relevance', 'Landing page experience']);
}
sheet.getRange(sheet.getLastRow() + 1, 1, out.length, out[0].length).setValues(out);
}
After a few weeks you can pivot the sheet by keyword and date and see which day a score moved, which you can then match against site releases, ad changes or a competitor arriving in the auction.
3. Broken landing page checker
Clicks that land on a 404 are paid for and cannot convert, and they usually start after a site update, a product being discontinued or a collection being renamed. This script collects every final URL from your enabled ads, keywords and Performance Max asset groups, requests each one once, and emails you any that do not come back with a 200 response.
Schedule it daily, or hourly for a shop that changes its catalogue often. MAX_URLS caps how many it checks in one run, so a very large account stays inside the time limit.
// Broken URL checker
// Collects the final URLs from enabled ads, keywords and Performance Max asset
// groups, requests each one once, and emails any that do not return a 200.
const CONFIG = {
EMAIL: '[email protected]',
MAX_URLS: 800 // stays well inside the daily URL fetch quota
};
function main() {
const urls = {};
addUrls(
'SELECT ad_group_ad.ad.final_urls FROM ad_group_ad ' +
"WHERE ad_group_ad.status = 'ENABLED' AND ad_group.status = 'ENABLED' AND campaign.status = 'ENABLED'",
row => row.adGroupAd.ad.finalUrls, urls);
addUrls(
'SELECT ad_group_criterion.final_urls FROM ad_group_criterion ' +
"WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status = 'ENABLED' " +
"AND ad_group.status = 'ENABLED' AND campaign.status = 'ENABLED'",
row => row.adGroupCriterion.finalUrls, urls);
addUrls(
'SELECT asset_group.final_urls FROM asset_group ' +
"WHERE asset_group.status = 'ENABLED' AND campaign.status = 'ENABLED'",
row => row.assetGroup.finalUrls, urls);
const list = Object.keys(urls).slice(0, CONFIG.MAX_URLS);
const broken = [];
list.forEach(url => {
try {
const code = UrlFetchApp.fetch(url, { muteHttpExceptions: true, followRedirects: true })
.getResponseCode();
if (code !== 200) broken.push(code + ' | ' + url);
} catch (e) {
broken.push('Failed to load | ' + url + ' | ' + e.message);
}
});
Logger.log('Checked ' + list.length + ' URLs, ' + broken.length + ' problems');
if (broken.length === 0) return;
MailApp.sendEmail(
CONFIG.EMAIL,
AdsApp.currentAccount().getName() + ': ' + broken.length + ' landing page problems',
'These final URLs did not return a 200 response:\n\n' + broken.join('\n'));
}
function addUrls(query, pick, urls) {
const rows = AdsApp.search(query);
while (rows.hasNext()) {
[].concat(pick(rows.next()) || []).forEach(url => { urls[url] = true; });
}
}
Some sites block automated requests and return a 403 even though the page works for a real visitor, so open any 403 in your own browser before you change anything. A 301 or 302 that ends on a working page counts as fine, because the script follows redirects.
4. N-gram search term analyser
Reading thousands of search terms one by one does not show you patterns, such as the word "free" appearing in 300 different searches that each spent a small amount. This script splits every search term from the last 30 days into one, two and three word phrases, adds up the impressions, clicks, cost, conversions and value behind each phrase, and writes the result to a Google Sheet, highest cost first.
Schedule it weekly or monthly. It reads the search terms report, so it covers your Search and standard Shopping campaigns but not Performance Max, whose search terms Google reports separately, and MIN_COST keeps phrases with trivial spend out of the sheet.
// N-gram search term analyser
// Splits every search term from the last 30 days into one, two and three word
// phrases, adds up the cost, conversions and value behind each phrase, and
// writes the result to a Google Sheet, highest cost first.
const CONFIG = {
SHEET_URL: 'https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit',
TAB: 'N-grams',
SIZES: [1, 2, 3],
MIN_COST: 5 // leave out phrases that spent less than this
};
function main() {
const query =
'SELECT search_term_view.search_term, metrics.impressions, metrics.clicks, ' +
'metrics.cost_micros, metrics.conversions, metrics.conversions_value ' +
'FROM search_term_view ' +
'WHERE segments.date DURING LAST_30_DAYS AND metrics.impressions > 0';
const stats = {};
const rows = AdsApp.search(query);
while (rows.hasNext()) {
const row = rows.next();
const words = row.searchTermView.searchTerm.toLowerCase().split(/\s+/).filter(Boolean);
const phrases = new Set();
CONFIG.SIZES.forEach(n => {
for (let i = 0; i + n <= words.length; i++) phrases.add(n + '|' + words.slice(i, i + n).join(' '));
});
phrases.forEach(key => {
const s = stats[key] || (stats[key] = { impr: 0, clicks: 0, cost: 0, conv: 0, value: 0 });
s.impr += Number(row.metrics.impressions);
s.clicks += Number(row.metrics.clicks);
s.cost += Number(row.metrics.costMicros) / 1e6;
s.conv += Number(row.metrics.conversions);
s.value += Number(row.metrics.conversionsValue);
});
}
const out = Object.keys(stats)
.filter(key => stats[key].cost >= CONFIG.MIN_COST)
.map(key => {
const s = stats[key];
const parts = key.split('|');
return [Number(parts[0]), parts[1], s.impr, s.clicks, round(s.cost), round(s.conv),
s.conv > 0 ? round(s.cost / s.conv) : '', s.cost > 0 ? round(s.value / s.cost) : ''];
})
.sort((a, b) => b[4] - a[4]);
const book = SpreadsheetApp.openByUrl(CONFIG.SHEET_URL);
const sheet = book.getSheetByName(CONFIG.TAB) || book.insertSheet(CONFIG.TAB);
sheet.clearContents();
sheet.appendRow(['Words', 'Phrase', 'Impressions', 'Clicks', 'Cost', 'Conversions', 'Cost per conversion', 'ROAS']);
if (out.length) sheet.getRange(2, 1, out.length, out[0].length).setValues(out);
}
function round(n) {
return Math.round(n * 100) / 100;
}
Sort by cost and look at the expensive phrases with no conversions, which are your negative keyword candidates, then sort by cost per conversion and look at the cheap phrases with strong conversions, which are worth adding as keywords or using as search themes in Performance Max.
5. Search terms with spend and no conversions
Where the n-gram script shows patterns, this one gives you the individual search terms that spent more than your threshold in the last 30 days without a single conversion, along with the campaign and ad group each one came through. The email subject line gives the total spent on those terms, which is a useful number to watch week to week.
Schedule it weekly and set MIN_COST to roughly half your target cost per conversion, which is low enough to catch irrelevant terms early.
// Search terms with spend and no conversions
// Emails the search terms from the last 30 days that spent more than your
// threshold without a single conversion, so you can decide on negatives.
const CONFIG = {
EMAIL: '[email protected]',
MIN_COST: 20, // account currency
MAX_ROWS: 50
};
function main() {
const query =
'SELECT campaign.name, ad_group.name, search_term_view.search_term, ' +
'metrics.clicks, metrics.cost_micros ' +
'FROM search_term_view ' +
'WHERE segments.date DURING LAST_30_DAYS AND metrics.conversions = 0 ' +
'AND metrics.cost_micros > ' + CONFIG.MIN_COST * 1e6;
const terms = [];
const rows = AdsApp.search(query);
while (rows.hasNext()) {
const row = rows.next();
terms.push({
term: row.searchTermView.searchTerm,
where: row.campaign.name + ' > ' + row.adGroup.name,
clicks: Number(row.metrics.clicks),
cost: Number(row.metrics.costMicros) / 1e6
});
}
if (terms.length === 0) return;
terms.sort((a, b) => b.cost - a.cost);
const total = terms.reduce((sum, t) => sum + t.cost, 0);
const lines = terms.slice(0, CONFIG.MAX_ROWS).map(t =>
t.cost.toFixed(2) + ' | ' + t.clicks + ' clicks | ' + t.term + ' | ' + t.where);
MailApp.sendEmail(
CONFIG.EMAIL,
AdsApp.currentAccount().getName() + ': ' + terms.length + ' search terms, ' +
total.toFixed(2) + ' spent with no conversions',
'Last 30 days, over ' + CONFIG.MIN_COST + ' each, highest spend first:\n\n' + lines.join('\n'));
}
Not every term on the list should become a negative. A term with a sensible meaning that has spent just over the threshold may only need more time, while a term that has nothing to do with what you sell can go straight into your negative list.
6. Monthly budget pacing alert
Google's daily budgets can spend up to twice the daily amount on a given day and are balanced over the month, which makes it hard to see from the interface whether you will land on your monthly figure. This script takes spend so far this month, projects it to the end of the month at the current rate, and emails you if the projection is above 110% or below 85% of the monthly budget you set.
Schedule it daily, put your monthly budget in MONTHLY_BUDGET, and adjust OVER and UNDER if you want a tighter band.
// Monthly budget pacing alert
// Compares spend so far this month with where it should be for your monthly
// budget, projects the month-end figure, and emails you if it is off pace.
const CONFIG = {
EMAIL: '[email protected]',
MONTHLY_BUDGET: 3000, // account currency
OVER: 1.1, // alert if projected spend is above 110% of budget
UNDER: 0.85 // alert if projected spend is below 85% of budget
};
function main() {
const tz = AdsApp.currentAccount().getTimeZone();
const now = new Date();
const year = Number(Utilities.formatDate(now, tz, 'yyyy'));
const month = Number(Utilities.formatDate(now, tz, 'M'));
const day = Number(Utilities.formatDate(now, tz, 'd'));
const hour = Number(Utilities.formatDate(now, tz, 'H'));
const daysInMonth = new Date(year, month, 0).getDate();
const elapsed = (day - 1 + hour / 24) / daysInMonth;
if (elapsed <= 0) return;
const rows = AdsApp.search(
'SELECT metrics.cost_micros FROM customer WHERE segments.date DURING THIS_MONTH');
let spend = 0;
while (rows.hasNext()) spend += Number(rows.next().metrics.costMicros) / 1e6;
const projected = spend / elapsed;
const ratio = projected / CONFIG.MONTHLY_BUDGET;
Logger.log('Spend ' + spend.toFixed(2) + ', projected ' + projected.toFixed(2));
if (ratio <= CONFIG.OVER && ratio >= CONFIG.UNDER) return;
MailApp.sendEmail(
CONFIG.EMAIL,
AdsApp.currentAccount().getName() + ': projected spend ' + Math.round(ratio * 100) + '% of budget',
'Spent so far this month: ' + spend.toFixed(2) + '\n' +
'Projected month end: ' + projected.toFixed(2) + '\n' +
'Monthly budget: ' + CONFIG.MONTHLY_BUDGET + '\n' +
'Days left: ' + (daysInMonth - day + 1));
}
The projection assumes the rest of the month spends at the same rate as the month so far, so it is rough in the first few days and more reliable after the first week.
7. Daily anomaly alert
A tracking tag that stops firing, a feed that gets suspended or a bid strategy change that goes wrong will usually show up as an unusual day in the account's numbers, often before anyone has spotted the cause. This script compares yesterday's clicks, cost and conversions with the average of the same weekday over the previous four weeks, so a Monday is compared with Mondays, and emails you about any move of 40% or more either way.
Schedule it daily in the early morning. MIN_BASELINE stops it alerting on metrics that are too small to judge, for example a 50% drop from two conversions to one.
// Daily anomaly alert
// Compares yesterday's clicks, cost and conversions with the average of the
// same weekday over the previous four weeks, and emails you about big moves.
const CONFIG = {
EMAIL: '[email protected]',
CHANGE: 0.4, // alert on a move of 40% or more either way
MIN_BASELINE: { clicks: 20, cost: 20, conversions: 3 } // ignore metrics too small to judge
};
function main() {
const tz = AdsApp.currentAccount().getTimeZone();
const today = Utilities.formatDate(new Date(), tz, 'yyyy-MM-dd');
const yesterday = shift(today, -1);
const start = shift(yesterday, -28);
const rows = AdsApp.search(
'SELECT segments.date, metrics.clicks, metrics.cost_micros, metrics.conversions ' +
'FROM customer ' +
"WHERE segments.date BETWEEN '" + start + "' AND '" + yesterday + "'");
const byDate = {};
while (rows.hasNext()) {
const row = rows.next();
byDate[row.segments.date] = {
clicks: Number(row.metrics.clicks),
cost: Number(row.metrics.costMicros) / 1e6,
conversions: Number(row.metrics.conversions)
};
}
const empty = { clicks: 0, cost: 0, conversions: 0 };
const latest = byDate[yesterday] || empty;
const past = [7, 14, 21, 28].map(n => byDate[shift(yesterday, -n)] || empty);
const alerts = [];
Object.keys(CONFIG.MIN_BASELINE).forEach(metric => {
const baseline = past.reduce((sum, d) => sum + d[metric], 0) / past.length;
if (baseline < CONFIG.MIN_BASELINE[metric]) return;
const change = (latest[metric] - baseline) / baseline;
if (Math.abs(change) >= CONFIG.CHANGE) {
alerts.push(metric + ': ' + latest[metric].toFixed(2) + ' yesterday against an average of ' +
baseline.toFixed(2) + ' (' + (change > 0 ? '+' : '') + Math.round(change * 100) + '%)');
}
});
if (alerts.length === 0) return;
MailApp.sendEmail(
CONFIG.EMAIL,
AdsApp.currentAccount().getName() + ': unusual day on ' + yesterday,
'Compared with the same weekday over the last four weeks:\n\n' + alerts.join('\n'));
}
function shift(dateString, days) {
const d = new Date(dateString + 'T12:00:00Z');
d.setUTCDate(d.getUTCDate() + days);
return Utilities.formatDate(d, 'UTC', 'yyyy-MM-dd');
}
A drop in conversions with clicks and cost steady is the classic sign of a tracking problem, so check your conversion tags before you change anything in the campaigns.
8. Stopped serving alert
When a card payment fails, an account gets suspended, a campaign reaches its end date or every ad in it is disapproved, spend stops, and unless someone sees Google's notification or is in the account that day, the gap can go unnoticed for days. This script lists campaigns that had impressions yesterday but have none so far today.
Schedule it once a day around midday. Running it early in the morning will flag campaigns that have not served yet today, especially low-volume ones and any with an ad schedule that starts later.
// Stopped serving alert
// Run it once a day around midday. It lists campaigns that had impressions
// yesterday but have none so far today, which usually means a billing,
// approval or budget problem.
const CONFIG = {
EMAIL: '[email protected]'
};
function main() {
const yesterday = campaignsWithImpressions('YESTERDAY');
const today = campaignsWithImpressions('TODAY');
const stopped = Object.keys(yesterday).filter(name => !today[name]);
if (stopped.length === 0) return;
MailApp.sendEmail(
CONFIG.EMAIL,
AdsApp.currentAccount().getName() + ': ' + stopped.length + ' campaigns have stopped serving',
'These campaigns had impressions yesterday and none so far today:\n\n' +
stopped.map(name => name + ' (' + yesterday[name] + ' impressions yesterday)').join('\n'));
}
function campaignsWithImpressions(range) {
const found = {};
const rows = AdsApp.search(
'SELECT campaign.name, metrics.impressions FROM campaign ' +
"WHERE campaign.status = 'ENABLED' AND metrics.impressions > 0 " +
'AND segments.date DURING ' + range);
while (rows.hasNext()) {
const row = rows.next();
found[row.campaign.name] = Number(row.metrics.impressions);
}
return found;
}
If every campaign appears on the list at once, check billing first. If it is one campaign, look at its status column, its end date and whether its ads or products have been disapproved.
9. Disapproved and limited ads alert
Disapprovals tend to arrive in batches after Google updates a policy, and they are easy to miss because a disapproved ad stops serving while the rest of the ad group carries on. This script emails you every enabled ad that is disapproved or approved with limits, with the policy topics Google has attached to each one.
Schedule it daily. There is nothing to configure apart from EMAIL.
// Disapproved and limited ads alert
// Emails every enabled ad that Google has disapproved or approved with limits,
// with the policy topics behind each one.
const CONFIG = {
EMAIL: '[email protected]'
};
function main() {
const query =
'SELECT campaign.name, ad_group.name, ad_group_ad.ad.id, ' +
'ad_group_ad.policy_summary.approval_status, ad_group_ad.policy_summary.policy_topic_entries ' +
'FROM ad_group_ad ' +
"WHERE ad_group_ad.status = 'ENABLED' AND ad_group.status = 'ENABLED' " +
"AND campaign.status = 'ENABLED' " +
"AND ad_group_ad.policy_summary.approval_status IN ('DISAPPROVED', 'APPROVED_LIMITED')";
const lines = [];
const rows = AdsApp.search(query);
while (rows.hasNext()) {
const row = rows.next();
const policy = row.adGroupAd.policySummary;
const topics = (policy.policyTopicEntries || []).map(t => t.topic).join(', ');
lines.push(policy.approvalStatus + ' | ' + row.campaign.name + ' > ' + row.adGroup.name +
' | ad ' + row.adGroupAd.ad.id + ' | ' + (topics || 'no topic given'));
}
if (lines.length === 0) return;
MailApp.sendEmail(
CONFIG.EMAIL,
AdsApp.currentAccount().getName() + ': ' + lines.length + ' ads disapproved or limited',
lines.join('\n'));
}
An ad that is approved with limits still serves, but not everywhere, so treat those as a lower priority than outright disapprovals. The policy topic name is what you search for in Google's advertising policies help pages to see what triggered it.
10. Performance Max channel report
Google now reports Performance Max results by channel, and this script puts that breakdown into a Google Sheet so you can see, for each campaign, how much of the last 30 days of spend went to Search, YouTube, Display, Discover, Gmail and Maps, along with the conversions, cost per conversion and ROAS from each.
Schedule it weekly and paste your sheet URL into SHEET_URL.
// Performance Max channel report
// Writes the last 30 days of spend, conversions and value for each Performance
// Max campaign, split by channel (Search, YouTube, Display, Discover, Gmail,
// Maps), to a Google Sheet.
const CONFIG = {
SHEET_URL: 'https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit',
TAB: 'PMax channels'
};
const NAMES = {
SEARCH: 'Search', SEARCH_PARTNERS: 'Search partners', CONTENT: 'Display',
YOUTUBE: 'YouTube', DISCOVER: 'Discover', GMAIL: 'Gmail', MAPS: 'Maps', MIXED: 'Mixed'
};
function main() {
const query =
'SELECT campaign.name, segments.ad_network_type, metrics.cost_micros, ' +
'metrics.conversions, metrics.conversions_value ' +
'FROM campaign ' +
"WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX' " +
'AND segments.date DURING LAST_30_DAYS';
const rows = AdsApp.search(query);
const data = [];
const totals = {};
while (rows.hasNext()) {
const row = rows.next();
const cost = Number(row.metrics.costMicros) / 1e6;
if (cost === 0) continue;
const name = row.campaign.name;
totals[name] = (totals[name] || 0) + cost;
data.push({
campaign: name,
channel: NAMES[row.segments.adNetworkType] || row.segments.adNetworkType,
cost: cost,
conv: Number(row.metrics.conversions),
value: Number(row.metrics.conversionsValue)
});
}
const out = data
.sort((a, b) => a.campaign.localeCompare(b.campaign) || b.cost - a.cost)
.map(d => [d.campaign, d.channel, round(d.cost), round(d.cost / totals[d.campaign] * 100) + '%',
round(d.conv), d.conv > 0 ? round(d.cost / d.conv) : '', round(d.value / d.cost)]);
const book = SpreadsheetApp.openByUrl(CONFIG.SHEET_URL);
const sheet = book.getSheetByName(CONFIG.TAB) || book.insertSheet(CONFIG.TAB);
sheet.clearContents();
sheet.appendRow(['Campaign', 'Channel', 'Cost', 'Share of spend', 'Conversions', 'Cost per conversion', 'ROAS']);
if (out.length) sheet.getRange(2, 1, out.length, out[0].length).setValues(out);
}
function round(n) {
return Math.round(n * 100) / 100;
}
If a large share of spend is going to a channel with weak results, look at the inputs that feed that channel before you add exclusions, for example the videos in your asset groups when YouTube is the weak channel.
11. Products with spend and no sales
In a shop with a few hundred products, a handful of them can take a noticeable share of spend without ever selling. This script adds up the last 30 days of Shopping and Performance Max spend by product and emails you every product that spent over your threshold with no conversions, along with its ID and title.
Schedule it weekly and set MIN_COST to around your average order value, so a product has had a fair chance before it appears.
// Products with spend and no sales
// Adds up the last 30 days of Shopping and Performance Max spend by product
// and emails the products that spent over your threshold without converting.
const CONFIG = {
EMAIL: '[email protected]',
MIN_COST: 30, // account currency
MAX_ROWS: 50
};
function main() {
const query =
'SELECT segments.product_item_id, segments.product_title, metrics.clicks, ' +
'metrics.cost_micros, metrics.conversions ' +
'FROM shopping_performance_view ' +
'WHERE segments.date DURING LAST_30_DAYS AND metrics.cost_micros > 0';
const products = {};
const rows = AdsApp.search(query);
while (rows.hasNext()) {
const row = rows.next();
const segments = row.segments || {};
const id = segments.productItemId;
if (!id) continue;
const p = products[id] || (products[id] = { title: segments.productTitle, clicks: 0, cost: 0, conv: 0 });
p.clicks += Number(row.metrics.clicks);
p.cost += Number(row.metrics.costMicros) / 1e6;
p.conv += Number(row.metrics.conversions);
}
const list = Object.keys(products)
.map(id => Object.assign({ id: id }, products[id]))
.filter(p => p.conv === 0 && p.cost >= CONFIG.MIN_COST)
.sort((a, b) => b.cost - a.cost);
if (list.length === 0) return;
const total = list.reduce((sum, p) => sum + p.cost, 0);
MailApp.sendEmail(
CONFIG.EMAIL,
AdsApp.currentAccount().getName() + ': ' + list.length + ' products, ' + total.toFixed(2) + ' spent, no sales',
'Last 30 days, over ' + CONFIG.MIN_COST + ' each:\n\n' +
list.slice(0, CONFIG.MAX_ROWS).map(p =>
p.cost.toFixed(2) + ' | ' + p.clicks + ' clicks | ' + p.id + ' | ' + p.title).join('\n'));
}
Before excluding a product, check its price against competitors in the Shopping results, its stock levels and its product page. A product that gets plenty of clicks but no sales is often priced above the market or has a weak page, while one with a low click-through rate may have a poor title or image.
12. Responsive search ad headline and description report
When the same headline is used in ten ad groups, Google reports its results separately in each one. This script adds up the last 30 days of impressions, clicks and conversions for every headline and description across all of your Search campaigns and writes the totals to a Google Sheet, so each line of copy appears once with its combined results.
Schedule it monthly. MIN_IMPRESSIONS keeps lines with too little data out of the sheet.
// RSA headline and description report
// Adds up the last 30 days of performance for every headline and description
// across all Search ad groups, so the same line used in ten ad groups shows
// as one row, and writes it to a Google Sheet.
const CONFIG = {
SHEET_URL: 'https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit',
TAB: 'RSA assets',
MIN_IMPRESSIONS: 100
};
function main() {
const query =
'SELECT asset.text_asset.text, ad_group_ad_asset_view.field_type, ' +
'metrics.impressions, metrics.clicks, metrics.conversions, metrics.cost_micros ' +
'FROM ad_group_ad_asset_view ' +
'WHERE segments.date DURING LAST_30_DAYS ' +
"AND ad_group_ad_asset_view.field_type IN ('HEADLINE', 'DESCRIPTION') " +
"AND campaign.advertising_channel_type = 'SEARCH' AND metrics.impressions > 0";
const assets = {};
const rows = AdsApp.search(query);
while (rows.hasNext()) {
const row = rows.next();
const key = row.adGroupAdAssetView.fieldType + '|' + row.asset.textAsset.text;
const a = assets[key] || (assets[key] = { impr: 0, clicks: 0, conv: 0, cost: 0, adGroups: 0 });
a.impr += Number(row.metrics.impressions);
a.clicks += Number(row.metrics.clicks);
a.conv += Number(row.metrics.conversions);
a.cost += Number(row.metrics.costMicros) / 1e6;
a.adGroups += 1;
}
const out = Object.keys(assets)
.filter(key => assets[key].impr >= CONFIG.MIN_IMPRESSIONS)
.map(key => {
const a = assets[key];
const parts = key.split('|');
return [parts[0], parts.slice(1).join('|'), a.adGroups, a.impr, a.clicks,
round(a.clicks / a.impr * 100) + '%', round(a.conv), round(a.conv / a.impr * 1000)];
})
.sort((a, b) => b[3] - a[3]);
const book = SpreadsheetApp.openByUrl(CONFIG.SHEET_URL);
const sheet = book.getSheetByName(CONFIG.TAB) || book.insertSheet(CONFIG.TAB);
sheet.clearContents();
sheet.appendRow(['Type', 'Text', 'Ads using it', 'Impressions', 'Clicks', 'CTR', 'Conversions', 'Conversions per 1,000 impressions']);
if (out.length) sheet.getRange(2, 1, out.length, out[0].length).setValues(out);
}
function round(n) {
return Math.round(n * 100) / 100;
}
Google counts an impression for every asset shown in an ad, so pinned headlines and the ones Google favours will have far more impressions than the rest. Compare click-through rate and conversions per 1,000 impressions between lines rather than raw totals, and use the strongest messages in new ads and in your Performance Max asset groups.
Which scripts to start with
For a lead generation account running mainly Search campaigns, start with the broken landing page checker, the stopped serving alert, the daily anomaly alert and the search terms with no conversions, because those four catch the problems that waste the most money fastest. Add the Quality Score scripts and the n-gram analyser once those are running.
For an ecommerce account, add the products with spend and no sales script and the Performance Max channel report to that first group, since most of the spend in a shop usually sits in Shopping and Performance Max.
Whatever the account, the budget pacing alert is worth setting up on day one if anyone signs off the monthly spend.
Limits worth knowing
A single script run stops after 30 minutes, so on a very large account the broken landing page checker may need its MAX_URLS setting lowered, or the checks split across two scripts. Emails sent with MailApp count against a daily email quota for scripts, which only matters if you run dozens of them. Google's own help pages say the search terms report leaves out terms searched by too few people, so expect the n-gram and search terms scripts to come in below your campaign totals.
These scripts show you where to look, and the decisions they lead to, such as adding negatives, excluding products or rewriting landing pages, still need someone who understands the account. If you are deciding whether that person should be in-house or an agency, our in-house vs agency Google Ads guide covers the costs of each, and our PPC audit checklist covers what to check by hand alongside the scripts.
If the scripts surface problems you are not sure how to fix, a Google Ads audit gives you a full view of where the account is working and where it is wasting spend.
Frequently asked questions
Do Google Ads scripts work with Performance Max campaigns?
Yes. Scripts can read Performance Max data, including spend and conversions by channel, product performance and asset group landing pages. Scripts 3, 10 and 11 in this guide use that data. Performance Max does not use keywords, so keyword-based scripts such as the Quality Score alert only apply to Search campaigns.
Do I need to know JavaScript to use these scripts?
No. Every script in this guide is complete, so you paste it into the script editor and change the settings in the CONFIG block at the top, such as your email address, a Google Sheet URL or a spend threshold. Knowing some JavaScript helps if you want to change what a script does.
How often should a Google Ads script run?
It depends on the job. Alerts that protect spend, such as the broken landing page checker, the stopped serving alert and the disapproved ads alert, should run daily. Reports that need more data to be useful, such as the n-gram analyser, the Performance Max channel report and the RSA headline and description report, are better weekly or monthly.
What is the difference between Google Ads scripts and automated rules?
Automated rules run a fixed action, such as pausing a keyword when cost per conversion goes over a set figure. Scripts can combine data from different reports, do calculations such as n-gram analysis or month-end projections, write to Google Sheets and send detailed emails, so they cover far more than rules can.
Can a script break my account?
A script can only do what its code tells it to, and you have to authorise it before it runs. Eleven of the twelve scripts in this guide only read data and send emails or write to a sheet, and the Low Quality Score alert adds a label. Use Preview before the first live run, which shows what a script would do without making changes to the account, although it will still send its email and write to its sheet.
