Yes, ChatGPT, Claude or Gemini can write usable Google Ads scripts for you. It only gets dangerous when you run the code without reading it. Language models know the basic structure well, but they mix up field names, reach for outdated methods and forget that costs come back in micros. A fixed workflow catches this: describe the task precisely, provide an excerpt from the docs, read the code, test it in preview and release changes only after a review.
In this article you get that workflow with prompt templates, four complete and annotated example scripts (read-only or with DRY_RUN = true) and the mistakes I keep finding in AI-generated code, each with a wrong and a correct version. How the AI inside Google Ads works, meaning Smart Bidding, Performance Max and AI Max, is covered in AI and automation in Google Ads. This article is about code that you bring into the account yourself.
As of: 8 October 2026. Based on the Google Ads Scripts developer documentation (limits page last updated on 30 September 2026) and the Google Ads API field reference for version v25. All scripts are constructed examples with no account data. Sources are listed at the end of the article.
What Google Ads scripts are and what they can do
Google Ads scripts are JavaScript programs that run directly inside your Google Ads account. Google describes them as a way to programmatically manage and query your Google Ads data using JavaScript in a browser-based IDE, for one account or for many accounts through a manager account (Google, Scripts overview). You do not need your own server.
Typical jobs:
- writing reports to Google Sheets automatically
- sending an email alert when costs or clicks fall outside the usual range
- checking landing page URLs for errors
- changing bids, budgets or labels according to fixed rules
According to Google, scheduled scripts run even when nobody is signed in (Authorization). Since March 2022 the new scripts experience has been available in its full version, with modern JavaScript including let, classes and for...of loops (Google Ads Developer Blog, March 2022). Google announced that it would start migrating legacy scripts automatically in September 2022 and move all scripts over in October 2022 (Developer Blog, August 2022). That matters for AI code: there is a lot of sample code from before that change on the web, and in my experience models like to mix those old patterns with the new ones.
The limits from the documentation
| Limit | Value according to Google |
|---|---|
| Runtime per execution in an advertiser account | 30 minutes, then cancelled |
| Runtime in a manager account with executeInParallel and a callback | up to 60 minutes, up to 50 accounts |
| Results per iterator | at most 50,000 by default |
| IDs in withIds() | at most 10,000 |
| Logging output | truncated at 100 KB |
| Authorized scripts per account | 250, beyond that an older script is temporarily deauthorized |
| Email recipients per day (MailApp) | 100 with a consumer Google account, 1,500 with Google Workspace |
| URL fetch calls per day (UrlFetchApp) | 20,000 with a consumer Google account, 100,000 with Google Workspace |
The first six rows come from the Google Ads scripts limits page. The last two come from the Google Apps Script quotas, because email, URL fetches and spreadsheets run through Apps Script services. These quotas are per user and reset 24 hours after the first request. One detail AI code almost never accounts for: if a script is cancelled after 30 minutes, Google says all changes made before the cancellation are applied. A script that changes bids and gets cut off halfway leaves you with a half-rebuilt account.
How to create a script
- In Google Ads, open Tools > Bulk actions > Scripts from the left-hand menu. Alternatively, search for "Scripts" in the Google Ads search bar.
- Click the plus icon and choose "New script". The same menu also offers script templates from Google.
- Give the script a name and paste the code into the editor.
- On the first preview, click "Authorize" when prompted. This is needed once per script; after that the script accesses the account on your behalf.
- Click "Preview". Results and logs appear in the "Changes / Logs" panel.
- Only when the preview looks right do you click "Run". This opens the "Script history" page with status and results.
The labels come from Google's getting started guide. Your account may differ slightly.
Preview versus run: the most important difference
According to Google, scripts executed in preview mode make no changes to the actual campaign data (preview documentation). The catch follows right after: preview mode only affects calls that use AdsApp as an entry point. Other services proceed as normal. An email sent with MailApp goes out, and a Google Sheet gets updated, whether you previewed the script or ran it. Preview also creates nothing. Code that creates a new object and uses it immediately behaves differently there than in a real run.
That leads to two rules for every script in this article:
- Emails only go out if
AdsApp.getExecutionInfo().isPreview()returns false. Google shows exactly this pattern in the ExecutionInfo reference. - Changes to the account sit behind a
DRY_RUNswitch. As long as it is true, the script only logs what it would do.
Scheduling and logs
You can set a schedule for each script. Google's own sample solutions show the range: the Link Checker should run hourly, the Account Summary daily at 3am or later, because according to Google, Google Ads statistics may be delayed by up to three hours. That delay affects every script that works with the previous day's numbers.
Scheduled scripts run on behalf of the person who authorized them. If that person loses access to the account, the script stops running. It is kept until someone with access authorizes it again. If the colleague who set up all your scripts leaves, you would otherwise only notice when the alerts stop arriving.
You write logs with console.log(). They appear in preview under "Changes / Logs" and, after a real run, in the script history. Anything beyond 100 KB gets truncated, so log summaries rather than every single row.
The workflow with AI
This is how I work, whether with ChatGPT, Claude or Gemini. In my experience, the context you provide matters more for the result than the choice of model. Prompt templates for tasks without code, from keyword clusters to the monthly report, are collected in ChatGPT prompts for Google Ads.
1. Describe the task precisely
"Make me a script for budget alerts" produces code that does something. Instead, describe:
- which data the script reads (resource, date range, campaign types)
- which threshold applies, and in which unit (account currency or micros)
- what happens at the end (log, email, spreadsheet, label)
- what the script must never do, for example change bids, budgets or statuses
2. Provide context
Copy the sections for the methods the script should use from the AdsApp reference into the prompt, plus the GAQL fields from the Google Ads API field reference. In my experience this noticeably reduces invented methods. Describe the account structure in abstract terms: "search campaigns and one Performance Max campaign, currency EUR, time zone Europe/Berlin". The model does not need campaign names, customer IDs or search terms.
3. Request the code, with clear rules
I use this template as a starting point. Replace the parts in square brackets:
You are an experienced developer of Google Ads scripts.
Task: [EXACT DESCRIPTION, e.g. "compare the current month's costs with a
monthly budget and send an email alert"]
Context:
- Environment: Google Ads scripts (current scripts experience, JavaScript
with let/const and for...of). Queries with AdsApp.search() and GAQL,
no AWQL columns.
- Account: [ABSTRACT STRUCTURE, e.g. "search campaigns only, currency EUR,
time zone Europe/Berlin"]. No real names or IDs.
- Reference excerpt: [PASTE SECTIONS FROM THE OFFICIAL DOCS]
Rules:
1. Only use methods and fields that appear in the reference excerpt or in
the official Google Ads scripts documentation. Do not invent anything.
If you are unsure, say so explicitly.
2. The script must not change the account. [OR: changes only when
DRY_RUN = false. The default is DRY_RUN = true, which only logs.]
3. GAQL returns costs in micros: divide by 1,000,000.
4. Build dates in the account's time zone
(AdsApp.currentAccount().getTimeZone()).
5. Only send emails when AdsApp.getExecutionInfo().isPreview() is false.
6. Limit data volumes (LIMIT or withLimit) and check the remaining time
with getRemainingTime() for long runs.
7. Comment every section in English and finish with a list of all methods
used, each with a link to its reference page.
4. Read the code
Before you start anything, read every line. My checklist:
- Every method appears in the Google Ads scripts or Apps Script reference. Open any links the model provides yourself.
- Every GAQL field exists in the field reference for the queried resource.
- In the results, fields are in lowerCamelCase:
metrics.cost_microsin the query becomesrow.metrics.costMicros(Google, reports in scripts). - Money values are consistently either micros or account currency.
- Methods that change campaigns, bids, budgets or statuses only appear inside a
DRY_RUNbranch. - You know what
MailApp,UrlFetchAppandSpreadsheetAppalready do in preview. - There are limits: LIMIT or withLimit, a check on the remaining time, a manageable number of emails.
A second model acting as reviewer finds additional mistakes. I paste the code into a fresh chat for this:
Review this Google Ads script like a strict code reviewer.
1. List every method called and every GAQL field, and state for each one
whether it exists in the official Google Ads scripts or Google Ads API
reference. Flag anything you cannot verify with certainty.
2. Name every place where the script changes data in the account,
sends emails or writes to spreadsheets.
3. Check units (micros or account currency), time zones and date boundaries.
4. Check whether the script will hit limits with large data volumes
(30 minutes runtime, 50,000 results per iterator).
Do not change the code. Only output a numbered list of issues.
[PASTE CODE]
5. Test in preview
Start the preview and read the logs. If the script reports that a field is undefined, log a single result row with console.log(JSON.stringify(row)). That shows you the real field names. Copying blindly does not help even with Google's own examples: on the best practices page, one example queries metrics.cost_micros and then logs row.metrics.cost, a field that was never queried.
If the script fails, this template helps:
The script fails in preview with this message:
[EXACT ERROR MESSAGE]
Log output of one result row, values replaced with placeholders:
[OUTPUT OF JSON.stringify(row), ANONYMIZED]
Find the cause. Only use methods from the official reference and
explain the change in two sentences before showing the corrected code.
6. Add safeguards
Test a new script first in an account where little is at stake, or restrict it to a single campaign, for example with campaign.name = 'Test campaign' in the GAQL query or through a label. In a manager account, start with a single client account.
7. Release in steps
DRY_RUN = true, preview, read the logs.DRY_RUN = true, real run via "Run", check the script history.DRY_RUN = false, but only for one campaign or one label.- Expand, and only then set a schedule.
Four example scripts to adapt
All four scripts read data with AdsApp.search() and GAQL, as Google recommends on its best practices page. The values in capitals at the top are examples that you adapt to your account. None of the scripts changes bids, budgets or statuses. Script 3 can mark ads with a label, but only if you deliberately set DRY_RUN to false.
Script 1: Budget pacing alert by email
The script compares costs from the first of the month up to yesterday with the pro-rata monthly budget and projects where you will land at the end of the month. If the account is outside the tolerance, you get an email. I deliberately leave out today, because it is still running and statistics can be delayed.
/**
* Budget pacing alert (read-only)
* Compares costs from the first of the month up to yesterday with the
* pro-rata monthly budget and sends an email if the account is spending
* too fast or too slowly. Changes nothing in the account.
*/
const MONTHLY_BUDGET = 3000; // monthly budget in account currency (example)
const UPPER_LIMIT = 1.15; // alert at 15 % above plan (example)
const LOWER_LIMIT = 0.85; // alert at 15 % below plan (example)
const EMAIL = 'you@example.com'; // alert recipient
function main() {
const account = AdsApp.currentAccount();
const timeZone = account.getTimeZone();
const now = new Date();
// Always build dates in the account's time zone
const day = Number(Utilities.formatDate(now, timeZone, 'd'));
const month = Number(Utilities.formatDate(now, timeZone, 'M'));
const year = Number(Utilities.formatDate(now, timeZone, 'yyyy'));
const daysInMonth = new Date(year, month, 0).getDate();
if (day === 1) {
console.log('First of the month: no complete day to compare yet.');
return;
}
const firstDay = Utilities.formatDate(now, timeZone, 'yyyy-MM') + '-01';
// 24 hours back gives yesterday in account time (do not schedule just after midnight)
const yesterday = Utilities.formatDate(
new Date(now.getTime() - 24 * 60 * 60 * 1000), timeZone, 'yyyy-MM-dd');
const query =
'SELECT metrics.cost_micros FROM customer ' +
"WHERE segments.date BETWEEN '" + firstDay + "' AND '" + yesterday + "'";
let costMicros = 0;
for (const row of AdsApp.search(query)) {
costMicros += Number(row.metrics.costMicros); // field name in lowerCamelCase
}
const cost = costMicros / 1000000; // micros to account currency
const daysDone = day - 1;
const plan = MONTHLY_BUDGET * daysDone / daysInMonth;
const forecast = cost / daysDone * daysInMonth;
const ratio = cost / plan;
const currency = account.getCurrencyCode();
const summary =
'Costs up to yesterday: ' + cost.toFixed(2) + ' ' + currency + '\n' +
'Plan up to yesterday: ' + plan.toFixed(2) + ' ' + currency + '\n' +
'Month-end projection: ' + forecast.toFixed(2) + ' ' + currency;
console.log(summary);
if (ratio > UPPER_LIMIT || ratio < LOWER_LIMIT) {
const subject = 'Budget pacing ' + account.getName() + ': ' +
Math.round(ratio * 100) + ' % of plan';
if (AdsApp.getExecutionInfo().isPreview()) {
console.log('Preview, no email. Subject would be: ' + subject);
} else {
MailApp.sendEmail(EMAIL, subject, summary);
}
}
}
Methods used: AdsApp.currentAccount() with getTimeZone(), getCurrencyCode() and getName() from the Account reference, Utilities.formatDate(), AdsApp.search(), AdsApp.getExecutionInfo().isPreview() and MailApp.sendEmail(). GAQL: resource customer, fields metrics.cost_micros and segments.date.
The customer resource covers the whole account. If you have separate budgets for different groups of campaigns, query campaign instead and filter with a condition on campaign.name. Schedule the script daily in the morning.
Script 2: Search terms with cost but no conversion, written to a spreadsheet
The script writes the most expensive search terms of the last 30 days that brought no conversion to a Google Sheet. It changes nothing in the account. You decide yourself which terms to exclude, and my negative keyword list helps with that.
/**
* Search terms with cost but no conversion (read-only in the account)
* Writes the most expensive search terms of the last 30 days without a
* conversion to a Google Sheet. Note: the sheet is written in preview too.
*/
const SPREADSHEET_URL = 'https://docs.google.com/spreadsheets/d/YOUR-SPREADSHEET-ID/edit';
const SHEET_NAME = 'Search terms without conversion';
const MIN_COST = 20; // minimum cost in account currency (example)
const MAX_ROWS = 500; // upper limit for the query
function main() {
const minCostMicros = Math.round(MIN_COST * 1000000); // threshold in micros
// search_term_view does not include Performance Max data
const query =
'SELECT search_term_view.search_term, campaign.name, ad_group.name, ' +
'metrics.clicks, metrics.cost_micros, metrics.conversions ' +
'FROM search_term_view ' +
'WHERE segments.date DURING LAST_30_DAYS ' +
'AND metrics.cost_micros > ' + minCostMicros + ' ' +
'ORDER BY metrics.cost_micros DESC ' +
'LIMIT ' + MAX_ROWS;
const output = [];
for (const row of AdsApp.search(query)) {
// Conversions are decimal numbers, fractions are possible
if (Number(row.metrics.conversions) > 0) {
continue;
}
output.push([
row.searchTermView.searchTerm,
row.campaign.name,
row.adGroup.name,
Number(row.metrics.clicks),
Number(row.metrics.costMicros) / 1000000,
]);
}
const header = ['Search term', 'Campaign', 'Ad group', 'Clicks', 'Cost'];
const spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
const sheet = spreadsheet.getSheetByName(SHEET_NAME) ||
spreadsheet.insertSheet(SHEET_NAME);
sheet.clearContents();
sheet.getRange(1, 1, 1, header.length).setValues([header]);
if (output.length > 0) {
sheet.getRange(2, 1, output.length, header.length).setValues(output);
}
console.log(output.length + ' search terms without conversion written.');
}
Methods used: AdsApp.search(), SpreadsheetApp.openByUrl(), getSheetByName(), insertSheet(), clearContents(), getRange() and setValues() from the Apps Script reference. GAQL: resource search_term_view with search_term_view.search_term, metrics.clicks, metrics.cost_micros and metrics.conversions.
Performance Max is missing from this report: according to the field reference, search_term_view does not include PMax data, and Google points to the campaign_search_term_view resource instead. LIMIT applies before the conversion filter in the code, so you may get fewer than 500 rows. The sheet is written even in preview, because spreadsheets are not an AdsApp call, so use a separate test sheet while testing. Everything is written with a single setValues() call rather than row by row, as Google recommends on its best practices page. Which other metrics you need for this kind of analysis is covered in Google Ads KPIs: which metrics actually matter.
Script 3: Link checker for final URLs with DRY_RUN
The script requests every final URL of active ads once and reports anything that does not respond with status code 200. With DRY_RUN = true it only logs and, after a real run, sends an email. With DRY_RUN = false the affected ads also get a label that you created in the account beforehand. A label does not change bids, budgets or statuses on its own, which makes it a good first change to practise with. Do check, though, whether automated rules or other scripts in your account react to labels.
/**
* Link checker for final URLs of active ads
* Requests every final URL once and reports anything that does not
* respond with 200. With DRY_RUN = true the script changes nothing in
* the account. With DRY_RUN = false affected ads get a label that you
* created in the account beforehand.
*/
const DRY_RUN = true; // true: only check and log
const LABEL_NAME = 'Broken link'; // must already exist in the account
const EMAIL = 'you@example.com';
const MAX_URLS = 300; // upper limit per run (example)
const TIME_BUFFER_SECONDS = 120; // reserve before the 30-minute limit
function main() {
const query =
'SELECT ad_group.id, ad_group_ad.ad.id, 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'";
// Check each URL only once, but remember which ads use it
const adsByUrl = new Map();
for (const row of AdsApp.search(query)) {
const urls = row.adGroupAd.ad.finalUrls || [];
for (const url of urls) {
if (!adsByUrl.has(url)) {
adsByUrl.set(url, []);
}
adsByUrl.get(url).push([String(row.adGroup.id), String(row.adGroupAd.ad.id)]);
}
}
const executionInfo = AdsApp.getExecutionInfo();
const broken = [];
let checked = 0;
for (const url of adsByUrl.keys()) {
if (checked >= MAX_URLS ||
executionInfo.getRemainingTime() < TIME_BUFFER_SECONDS) {
console.log('Limit reached, check the rest in the next run.');
break;
}
checked++;
let status;
try {
// muteHttpExceptions: 404 or 500 do not throw, they return the code
status = UrlFetchApp.fetch(url, {muteHttpExceptions: true}).getResponseCode();
} catch (e) {
status = 'Error: ' + e.message; // e.g. domain unreachable
}
if (status !== 200) {
broken.push({url: url, status: status, adIds: adsByUrl.get(url)});
}
}
console.log(checked + ' of ' + adsByUrl.size + ' URLs checked, ' +
broken.length + ' with problems.');
if (broken.length === 0) {
return;
}
const report = broken.map(function(item) {
return item.status + ' ' + item.url + ' (' + item.adIds.length + ' ads)';
}).join('\n');
console.log(report);
if (DRY_RUN) {
console.log('DRY_RUN: no labels applied.');
} else {
const labelExists = AdsApp.labels()
.withCondition("label.name = '" + LABEL_NAME + "'")
.get()
.hasNext();
if (!labelExists) {
console.log('Label "' + LABEL_NAME + '" is missing. Create it in the account first.');
} else {
for (const item of broken) {
const ads = AdsApp.ads().withIds(item.adIds).get();
while (ads.hasNext()) {
ads.next().applyLabel(LABEL_NAME);
}
}
}
}
if (!executionInfo.isPreview()) {
MailApp.sendEmail(EMAIL, 'Link checker: ' + broken.length + ' broken URLs', report);
}
}
Methods used: AdsApp.search(), AdsApp.getExecutionInfo() with getRemainingTime() and isPreview(), UrlFetchApp.fetch() with getResponseCode(), AdsApp.labels().withCondition(), AdsApp.ads().withIds() with pairs of ad group ID and ad ID as described in the AdSelector reference, applyLabel() and MailApp.sendEmail(). GAQL: resource ad_group_ad with ad_group_ad.ad.final_urls, a repeated field.
UrlFetchApp follows redirects by default, so a 301 to a working page counts as 200 (UrlFetchApp reference). Every request counts against the daily URL fetch quota, and the requests also happen in preview, because they do not go through AdsApp. That is harmless here, since the script only reads pages. According to the reference, applyLabel() fails if the label does not exist, which is why the script checks first. This simple version only checks the final URLs of ads, without tracking templates, custom parameters or mobile URLs. Google's full Link Checker also checks keywords and sitelinks and works through large accounts over several hourly runs. In my experience some servers block automated requests and return 403 even though the page works for humans. Check hits like that by hand.
Script 4: Anomaly alert for clicks and costs
The script compares yesterday with the average of the same weekday over the previous four weeks and sends an alert when the deviation is large. Comparing with the same weekday is more robust than comparing with the day before, because weekdays perform very differently in most of the accounts I see.
/**
* Anomaly alert for clicks and costs (read-only)
* Compares yesterday with the average of the same weekday over the
* previous four weeks and sends an email if the deviation is large.
*/
const WEEKS_BACK = 4; // number of comparison weeks
const THRESHOLD = 0.4; // alert at 40 % deviation (example)
const MIN_CLICKS = 30; // below this the comparison is too shaky (example)
const EMAIL = 'you@example.com';
function main() {
const account = AdsApp.currentAccount();
const timeZone = account.getTimeZone();
const currency = account.getCurrencyCode();
const dayMs = 24 * 60 * 60 * 1000;
const now = Date.now();
// Date n days ago in the account's time zone
const dateDaysAgo = function(n) {
return Utilities.formatDate(new Date(now - n * dayMs), timeZone, 'yyyy-MM-dd');
};
const yesterday = dateDaysAgo(1);
const compareDays = [];
for (let week = 1; week <= WEEKS_BACK; week++) {
compareDays.push(dateDaysAgo(1 + 7 * week));
}
const firstDay = compareDays[compareDays.length - 1];
const query =
'SELECT segments.date, metrics.clicks, metrics.cost_micros FROM customer ' +
"WHERE segments.date BETWEEN '" + firstDay + "' AND '" + yesterday + "'";
const byDate = new Map();
for (const row of AdsApp.search(query)) {
byDate.set(row.segments.date, {
clicks: Number(row.metrics.clicks),
cost: Number(row.metrics.costMicros) / 1000000,
});
}
// The API does not return days on which all metrics are 0: count them as 0
const valuesFor = function(date) {
return byDate.get(date) || {clicks: 0, cost: 0};
};
const last = valuesFor(yesterday);
let sumClicks = 0;
let sumCost = 0;
for (const date of compareDays) {
sumClicks += valuesFor(date).clicks;
sumCost += valuesFor(date).cost;
}
const avgClicks = sumClicks / WEEKS_BACK;
const avgCost = sumCost / WEEKS_BACK;
if (avgClicks < MIN_CLICKS) {
console.log('Too few clicks for a meaningful comparison.');
return;
}
const clickChange = (last.clicks - avgClicks) / avgClicks;
const costChange = avgCost > 0 ? (last.cost - avgCost) / avgCost : 0;
const summary =
'Yesterday (' + yesterday + '): ' + last.clicks + ' clicks, ' +
last.cost.toFixed(2) + ' ' + currency + '\n' +
'Same-weekday average: ' + avgClicks.toFixed(1) + ' clicks, ' +
avgCost.toFixed(2) + ' ' + currency + '\n' +
'Deviation: clicks ' + Math.round(clickChange * 100) + ' %, cost ' +
Math.round(costChange * 100) + ' %';
console.log(summary);
if (Math.abs(clickChange) > THRESHOLD || Math.abs(costChange) > THRESHOLD) {
const subject = 'Anomaly in ' + account.getName();
if (AdsApp.getExecutionInfo().isPreview()) {
console.log('Preview, no email. Subject would be: ' + subject);
} else {
MailApp.sendEmail(EMAIL, subject, summary);
}
}
}
Methods used: AdsApp.currentAccount() with getTimeZone(), getCurrencyCode() and getName(), Utilities.formatDate(), AdsApp.search(), isPreview() and MailApp.sendEmail(). GAQL: resource customer with segments.date, metrics.clicks and metrics.cost_micros.
Google evaluates GAQL date ranges in the account's time zone (GAQL date ranges), which is why the script builds its own dates in that time zone too. When a query is segmented, the API does not return rows in which all selected metrics are 0 (Google, zero metrics). An AI script that simply averages over the rows it received will then overstate the average. I deliberately leave conversions out of this alert: in my experience they often keep coming in for days after the click, and the previous day would almost always look too weak. Schedule the script daily at 3am or later. If you want more, Google's solutions library has the Account Anomaly Detector as a fuller version.
Typical mistakes in AI code
These are the mistakes I find most often in AI-generated scripts. The evidence is in the reference linked below the table.
| Mistake | How to spot it | Correct |
|---|---|---|
| AWQL columns from old code | conditions such as 'Clicks > 10' or 'Cost > 50' | GAQL fields such as 'metrics.clicks > 10', Google explicitly recommends GAQL over AWQL |
| Query field names used in the results | row.metrics.cost_micros is undefined | row.metrics.costMicros, result fields come back in lowerCamelCase |
| Micros confused with currency | threshold of 50 against cost_micros, the script fires on almost every click | multiply the threshold by 1,000,000 or divide the result by 1,000,000 |
| Outdated methods | getAveragePosition(), getRemainingGetQuota() | according to the reference, getAveragePosition() has returned only null since the end of September 2019, and the quota methods are deprecated because the limit no longer exists |
| Invented methods | campaign.getCost() or withStatus('ENABLED') on a selector | costs via getStatsFor(...).getCost() or GAQL, status via withCondition() |
| Search and Display campaigns only | AdsApp.campaigns() finds no Performance Max, Shopping or Video campaigns | performanceMaxCampaigns(), shoppingCampaigns(), videoCampaigns() or GAQL on campaign |
| No limits | a loop over all keywords without withLimit(), no check on remaining time | LIMIT or withLimit() and getRemainingTime() |
| Time zone ignored | date built with new Date() and toISOString() | Utilities.formatDate() with the account's time zone |
| Preview misunderstood | email or spreadsheet sent "just for testing" in preview | check isPreview(), use a test sheet |
| Missing zero days | average taken only over the days the API returned | count missing days as 0 |
Table scrolls sideways
Evidence: CampaignSelector (GAQL conditions, costs in micros), best practices (GAQL over AWQL, search over report), Stats (getCost() in account currency, getAveragePosition() deprecated), ExecutionInfo (quota methods deprecated), AdsApp (campaigns() returns search and display campaigns).
Three of these mistakes as code, each wrong and correct:
// WRONG: AWQL column from old sample code, no date range
const oldSelector = AdsApp.campaigns()
.withCondition('Clicks > 10')
.get();
// CORRECT: GAQL field. Conditions on stats fields require a date range
const newSelector = AdsApp.campaigns()
.withCondition('metrics.clicks > 10')
.forDateRange('LAST_30_DAYS')
.get();
const rows = AdsApp.search(
'SELECT campaign.name, metrics.cost_micros FROM campaign ' +
'WHERE segments.date DURING LAST_7_DAYS');
for (const row of rows) {
// WRONG: field name as in the query, micros read as euros
// if (row.metrics.cost_micros > 50) ...
// CORRECT: lowerCamelCase and conversion to account currency
const cost = Number(row.metrics.costMicros) / 1000000;
if (cost > 50) {
console.log(row.campaign.name + ': ' + cost.toFixed(2));
}
}
// WRONG: toISOString() returns the date in UTC, not in account time
const wrongDate = new Date().toISOString().slice(0, 10);
// CORRECT: date in the account's time zone
const rightDate = Utilities.formatDate(
new Date(), AdsApp.currentAccount().getTimeZone(), 'yyyy-MM-dd');
Against invented methods, only one thing helps: look up every method in the reference. If it is not there, it does not exist, however plausible the name sounds.
Security and data protection
No customer data in AI chats. To write the code, the model needs the structure of your data, not the data itself. Search terms can contain names, addresses or phone numbers that people typed into Google. Customer lists, CRM exports and email addresses belong in a chat even less. If you paste a log line while debugging, replace the values with placeholders first.
Check your plan. Whether a provider reuses your inputs depends on the plan. For the Gemini API, for example, Google states on its pricing page that content from the free tier is used to improve its products, while content on the paid tier is not. I have put together what the models cost via API in my AI API pricing comparison.
No credentials in prompts. Never paste passwords, verification codes, API keys or developer tokens into a chat. Google Ads scripts do not need them anyway: the script gets its access through "Authorize" with your Google account. If a script calls an external service with a key, enter the key yourself in the editor. It is then readable by anyone who can open the script. How to protect access to the account itself is covered in Secure your Google Ads account.
Changes only after a review. Any script that changes something in the account gets read by a second person before DRY_RUN goes to false. Keep a record of who authorized which script, because it runs on that person's behalf. And remember the cancellation after 30 minutes: whatever was changed up to then stays changed.
Limits: when the API, Editor or rules are a better fit
Google draws the line between the tools itself in the scripts overview: the Google Ads API is meant for building your own software and infrastructure, and for bulk management without code Google points to automated rules, bulk uploads and Google Ads Editor.
| Task | Better fit |
|---|---|
| a simple recurring action without custom logic, such as pausing a campaign at fixed times | automated rules |
| large one-off changes, restructuring the account | Google Ads Editor or bulk uploads |
| your own dashboard, database, a tool for many accounts with its own interface | Google Ads API |
| checks, alerts, reports in spreadsheets, rules with custom logic | scripts |
| tasks that need more than 30 minutes of processing | split across several runs, or the API |
Scripts, MCP and AI agents
A script is fixed code. It does the same thing on every run, and you can read in advance what it will do. An AI agent connected to the Google Ads API through MCP (Model Context Protocol), on the other hand, only decides at runtime which queries to run. That is flexible for analysis questions but harder to control. For recurring checks I prefer a script that has been reviewed once over an agent that decides anew every time. How agents work with Google Ads and where their limits are is something I cover in Controlling Google Ads with AI agents.
Conclusion: AI writes, you are responsible
AI takes the typing off your hands when you write scripts, not the responsibility. Give the model a precise task and an excerpt from the reference, read the code against the checklist, test in preview and remember that emails and spreadsheets still run there. Changes to the account sit behind DRY_RUN and only go live after a review, one step at a time.
If you want to set up automation in your marketing properly or need a second pair of eyes on AI code, my AI consulting starts with an AI audit for €700. If a recurring marketing task, such as a report or an alert, should simply be built and run, AI automation is the better fit. If you would rather hand over account management entirely, managing your Google Ads is available from €1,000 per month, with a 3-month start phase and cancellable monthly after that.
Sources
- Google for Developers, Google Ads scripts, overview: developers.google.com/google-ads/scripts/docs/start
- Google for Developers, Google Ads scripts, getting started: developers.google.com/google-ads/scripts/docs/getting-started
- Google for Developers, Google Ads scripts, limits: developers.google.com/google-ads/scripts/docs/limits
- Google for Developers, Google Ads scripts, preview mode: developers.google.com/google-ads/scripts/docs/preview
- Google for Developers, Google Ads scripts, authorization: developers.google.com/google-ads/scripts/docs/authorization
- Google for Developers, Google Ads scripts, best practices: developers.google.com/google-ads/scripts/docs/best-practices
- Google for Developers, Google Ads scripts, reports: developers.google.com/google-ads/scripts/docs/concepts/reports
- Google for Developers, reference for AdsApp, Account, Ad, AdSelector, CampaignSelector, Stats, ExecutionInfo: developers.google.com/google-ads/scripts/docs/reference/adsapp/adsapp
- Google for Developers, solutions Link Checker, Account Summary, Account Anomaly Detector: developers.google.com/google-ads/scripts/docs/solutions/link-checker
- Google for Developers, Google Ads API, GAQL date ranges: developers.google.com/google-ads/api/docs/query/date-ranges
- Google for Developers, Google Ads API, zero metrics: developers.google.com/google-ads/api/docs/reporting/zero-metrics
- Google for Developers, Google Ads API v25, search_term_view fields: developers.google.com/google-ads/api/fields/v25/search_term_view
- Google for Developers, Google Ads API v25, ad_group_ad fields: developers.google.com/google-ads/api/fields/v25/ad_group_ad
- Google for Developers, Apps Script, quotas: developers.google.com/apps-script/guides/services/quotas
- Google for Developers, Apps Script, UrlFetchApp: developers.google.com/apps-script/reference/url-fetch/url-fetch-app
- Google Ads Developer Blog, New Google Ads scripts experience (14 March 2022): ads-developers.googleblog.com
- Google Ads Developer Blog, Google Ads Scripts migration office hours (2 August 2022): ads-developers.googleblog.com
- Google AI for Developers, Gemini API, pricing: ai.google.dev/gemini-api/docs/pricing
As of: 8 October 2026




