Skip to content
Online marketing in the agent era
ROA·Marketing
Menu
PPCAutomation

Google Ads Scripts: Automate PPC Like a Pro in 2026

Stop manually adjusting bids and budgets. Master Google Ads Scripts with real code examples for bid management, alerts, and search term mining that save 10+ hours per week.

Lines of JavaScript code on a dark IDE screen, representing Google Ads Scripts automation

Key Takeaways

  • Google Ads Scripts is a JavaScript runtime embedded in your Google Ads account. You write or paste JavaScript, schedule it…
  • Smart Bidding handles per-auction bid optimization. AI agents handle strategy, target adjustment, and anomaly reasoning —…
  • Start in preview mode. Every script has a Preview button in the Google Ads Scripts editor. Run it there first — it shows logs…
  • The line between scripts and AI agents is blurring, but the division of labor is clear:

Google Ads Scripts automate the repetitive, error-prone tasks that eat 60% of a PPC manager’s week — budget pacing, search term mining, anomaly detection, and bid adjustments. In 2026, they’re not a replacement for Smart Bidding or AI agents; they’re the glue that connects them, handling custom logic no built-in tool covers. And they run inside your Google Ads account for free.

The script engine inside Google Ads is over a decade old, but it’s never been more useful than right now. As AI agents and Smart Bidding absorb the high-level optimization work, scripts handle the edges: the custom budget rules for a multi-brand account, the alert when a landing page 404s, the weekly report formatted exactly how your client wants it. Every PPC team we work with runs at least three scripts in production. Here’s the stack that’s working in 2026.

What Google Ads Scripts actually are

Google Ads Scripts is a JavaScript runtime embedded in your Google Ads account. You write or paste JavaScript, schedule it (hourly, daily, weekly, or on a custom trigger), and it executes against your account via the Google Ads API — no external server, no API key management, no deployment pipeline.

What changed in 2026 is the execution environment. Scripts now support ES6+ syntax (arrow functions, template literals, let/const), have a 30-minute timeout (up from 6 minutes), and can process accounts 3-5x faster than the pre-2026 runtime. The UrlFetchApp service lets scripts call external APIs, which means you can pull in inventory levels from your warehouse, CRM lead quality scores, or weather data — and adjust campaigns accordingly.

Why scripts still matter in an AI agent world

Smart Bidding handles per-auction bid optimization. AI agents handle strategy, target adjustment, and anomaly reasoning — topics we’ve covered in depth in our guides on AI agents managing Google Ads campaigns, building custom reporting agents, and agentic bidding workflows. The bidding layer underneath all of it also changed in June 2026 — Smart Bidding Exploration, standalone Target CPA/ROAS, and more — so see our June 2026 bidding changes roundup before wiring new scripts around bid strategies.

Scripts sit below both of them. They’re for the plumbing: the exact budget distribution rule your CFO demands, the Slack notification when spend spikes, the custom spreadsheet format your client has used since 2018. An AI agent gives you a recommendation. A script executes a deterministic rule. Both belong in your stack. For simpler, no-code automations that don’t require JavaScript — like pausing underperforming ads or adjusting budgets on a schedule — Google Ads’ built-in Automated Rules are a faster alternative.

The 4 scripts every account should run

1. Budget pacer with overspend guard

This script checks campaign spend against daily budget at a configurable cadence — every hour if you’re running it hourly. If a campaign has spent more than its proportional budget (e.g., more than 50% by noon), it either sends an alert or pauses the campaign.

function main() {
  var today = new Date();
  var hourOfDay = today.getHours();
  var expectedPct = (hourOfDay / 24) * 100;
  var threshold = 1.3; // 30% overspend threshold

  var campaignIterator = AdsApp.campaigns()
    .withCondition('Status = ENABLED')
    .withCondition('AdvertisingChannelType = SEARCH')
    .get();

  while (campaignIterator.hasNext()) {
    var campaign = campaignIterator.next();
    var stats = campaign.getStatsFor('TODAY');
    var cost = stats.getCost();
    var budget = campaign.getBudget().getAmount();

    if (budget > 0) {
      var actualPct = (cost / budget) * 100;
      if (actualPct > expectedPct * threshold) {
        Logger.log('OVERPACE: ' + campaign.getName() +
          ' spent ' + cost.toFixed(2) + ' (' + actualPct.toFixed(1) + '%)' +
          ' vs expected ' + expectedPct.toFixed(1) + '%');
        // Uncomment to auto-pause: campaign.pause();
      }
    }
  }
}

Run this hourly. At minimum, it logs pacing anomalies. If you trust it, uncomment the pause line for campaigns that are clearly overspending. Pair it with a Slack webhook via UrlFetchApp and you’ll know within the hour, not at end-of-month reconciliation. For a full picture of how scripts feed into broader budget planning, see our guide on PPC Budget Forecasting & Planning Tools.

2. Search term n-gram miner

The biggest time sink in PPC management is search term review. A human scans maybe 10% of search terms in a typical account. This script processes every search term from the past 7 days, filters out terms below a conversion threshold, builds n-grams (single words, two-word phrases, three-word phrases) from the junk queries, and suggests negatives.

function main() {
  var report = AdsApp.report(
    'SELECT SearchTermView.search_term, ' +
    'Metrics.impressions, Metrics.clicks, Metrics.conversions, Metrics.cost ' +
    'FROM search_term_view ' +
    'WHERE segments.date DURING LAST_7_DAYS ' +
    'AND Metrics.impressions > 0'
  );

  var negativeCandidates = {}; // phrase -> { impressions, cost }
  var rows = report.rows();

  while (rows.hasNext()) {
    var row = rows.next();
    var term = row['SearchTermView.search_term'];
    var conversions = parseInt(row['Metrics.conversions']) || 0;
    var cost = parseFloat(row['Metrics.cost']) || 0;
    var impressions = parseInt(row['Metrics.impressions']) || 0;

    // Skip converting terms
    if (conversions > 0) continue;
    // Only look at terms with enough spend to matter
    if (cost < 5) continue;

    // Extract bigrams (two-word phrases)
    var words = term.toLowerCase().split(/\s+/);
    for (var i = 0; i < words.length - 1; i++) {
      var bigram = words[i] + ' ' + words[i + 1];
      if (!negativeCandidates[bigram]) {
        negativeCandidates[bigram] = { impressions: 0, cost: 0 };
      }
      negativeCandidates[bigram].impressions += impressions;
      negativeCandidates[bigram].cost += cost;
    }
  }

  Logger.log('=== Negative keyword candidates ===');
  for (var phrase in negativeCandidates) {
    if (negativeCandidates[phrase].cost > 20 &&
        negativeCandidates[phrase].impressions > 50) {
      Logger.log(phrase + ' | $' + negativeCandidates[phrase].cost.toFixed(2) +
        ' | ' + negativeCandidates[phrase].impressions + ' impressions');
    }
  }
}

Review the output weekly. Add the obvious junk as phrase-match negatives. One pass replaces 2-3 hours of manual search term audit. Note that Google updated search term reporting in July 2026 to replace literal AI-generated query matches with “best approximation of user intent” — see our guide on AI Search Terms Reporting Changes for how this affects script-based term mining.

3. Low-CTR ad group detector

Quality Score isn’t a KPI you optimize directly, but low CTR is the biggest drag on it. This script finds ad groups where CTR has collapsed, flagging them before they drag down your whole account.

function main() {
  var CTR_THRESHOLD = 0.015; // 1.5%
  var IMPRESSION_THRESHOLD = 200;

  var agIterator = AdsApp.adGroups()
    .withCondition('Status = ENABLED')
    .get();

  while (agIterator.hasNext()) {
    var adGroup = agIterator.next();
    var stats = adGroup.getStatsFor('LAST_7_DAYS');
    var impressions = stats.getImpressions();
    var clicks = stats.getClicks();
    var ctr = impressions > 0 ? clicks / impressions : 0;

    if (impressions > IMPRESSION_THRESHOLD && ctr < CTR_THRESHOLD) {
      Logger.log('LOW CTR: ' + adGroup.getName() +
        ' | Campaign: ' + adGroup.getCampaign().getName() +
        ' | Impressions: ' + impressions +
        ' | CTR: ' + (ctr * 100).toFixed(2) + '%');
    }
  }
}

Low CTR means your ad isn’t matching searcher intent. The fix is usually ad copy, not bid adjustments. If your ad copy is strong but conversions still lag, the issue often lives on the landing page — our PPC Landing Page Optimization guide covers how to bridge that gap. For a deeper dive on the mechanics behind CTR and ad rank, see our complete Quality Score guide.

4. Conversion drop alert

Conversion tracking breaks more often than anyone wants to admit — landing page changes, form plugin updates, GTM container edits. This script compares today’s conversions to the same day last week and alerts on a drop.

function main() {
  var report = AdsApp.report(
    'SELECT campaign.name, metrics.conversions ' +
    'FROM campaign ' +
    'WHERE segments.date = TODAY ' +
    'AND campaign.status = ENABLED'
  );

  var todayConversions = 0;
  var rows = report.rows();
  while (rows.hasNext()) {
    var row = rows.next();
    todayConversions += parseInt(row['metrics.conversions']) || 0;
  }

  // Same-day-last-week baseline
  var lastWeekReport = AdsApp.report(
    'SELECT metrics.conversions ' +
    'FROM campaign ' +
    'WHERE segments.date = ' + getLastWeekSameDay() +
    'AND campaign.status = ENABLED'
  );

  var lastWeekConversions = 0;
  var lwRows = lastWeekReport.rows();
  while (lwRows.hasNext()) {
    lastWeekConversions += parseInt(lwRows.next()['metrics.conversions']) || 0;
  }

  if (lastWeekConversions > 5 && todayConversions < lastWeekConversions * 0.5) {
    Logger.log('⚠️ CONVERSION DROP: Today ' + todayConversions +
      ' vs last week ' + lastWeekConversions + ' (-' +
      Math.round((1 - todayConversions / lastWeekConversions) * 100) + '%)');
  }
}

function getLastWeekSameDay() {
  var d = new Date();
  d.setDate(d.getDate() - 7);
  return Utilities.formatDate(d, AdsApp.currentAccount().getTimeZone(), 'yyyy-MM-dd');
}

If you’re running server-side conversion tracking — which we strongly recommend for data integrity — this script is your canary. When it fires, check your tracking before you touch any bid. Our server-side tracking setup guide covers the plumbing, and for agencies managing many accounts, bulk account linking to GA4 turns a day of conversion-setup busywork into a single pass.

How to deploy scripts safely

Start in preview mode. Every script has a Preview button in the Google Ads Scripts editor. Run it there first — it shows logs and errors without making changes.

Comment out destructive actions. Notice the pattern above: Logger.log() first, campaign.pause() commented out. Run scripts in log-only mode for two weeks before letting them touch your account.

Use labels as kill switches. Add a label like “Script Paused” to any campaign you want scripts to ignore. Check for it at the top of every script:

if (campaign.labels().withCondition("Name = 'Script Paused'").get().hasNext()) {
  continue; // Skip this campaign
}

Schedule conservatively. Scripts that read data but don’t write can run hourly. Scripts that pause campaigns or add negatives: once daily, with a human reviewing the logs. No script that touches budget or bids should run unattended for the first month.

Scripts + AI agents = the real 2026 stack

The line between scripts and AI agents is blurring, but the division of labor is clear:

  • Scripts handle deterministic logic — rules you’d write in a flowchart. If X, then Y. Every time.
  • AI agents handle probabilistic decisions — “conversions are down, is it seasonality, a broken landing page, or competitor activity?” They reason across signals a script can’t access.

Your 2026 stack should have both. Scripts do the hourly checks no human has time for. AI agents handle the strategy layer above Smart Bidding — see our deep dive on how AI agents optimize PPC bids automatically. Together, they compress an 8-hour manual workflow into a 30-minute review session.

The account that runs with neither is the one that spends $500 on dead clicks before someone notices the tracking pixel broke at 3 AM.

Where to start

Open Tools & Settings → Bulk Actions → Scripts in your Google Ads account. Paste in the budget pacer first — it’s the lowest-risk, highest-visibility script. Run it in preview. Check the logs. When you trust it, add the search term miner. Then the conversion drop alert.

Google’s official script documentation is thorough. The solutions library has production-tested templates for bidding, reporting, and account hygiene.

The scripts above took less than an hour to customize and deploy. They’ve been running in production accounts since Q1 2026 and continue performing through Q3 2026 as Google Ads evolves. Every one caught an overspend, a dead conversion tracker, or a batch of junk search terms within its first week. That’s not an exceptional result — it’s what happens when you stop trusting manual review to catch everything.

Frequently Asked Questions

Will AI agents replace human PPC managers?

AI agents will handle the mechanistic tasks — bid adjustments, budget pacing, search term audits — but human strategy remains essential. The winning approach in 2026 is augmentation: let AI run the daily optimizations while humans set strategy, interpret anomalies, and manage client relationships. Our Google Ads expert skill at roa-marketing.com/skills/google-ads-expert/ is built for exactly this hybrid workflow.

How do AI agents optimize PPC bids automatically?

AI agents combine real-time performance data with predefined rules to adjust bids across campaigns. They analyze conversion patterns by hour, device, location, and audience segment — then shift budget to what’s working. Unlike Google’s Smart Bidding, an external AI agent can factor in offline conversions, CRM data, and cross-platform performance simultaneously.

R

Rogozan Oliviu-Alexandru

ROA Marketing publishes deep, practical playbooks on PPC, SEO, and AI-driven marketing. We test everything we write about on live campaigns.

More articles →
🤖
New Course

Connect Any AI Agent to Google Ads

Build an AI agent that manages campaigns autonomously. MCC setup, OAuth, MCP server — full source code included.

$5 on Gumroad →
📘
Bestseller

Google Ads Expert — Master PPC

12 modules, real CPC benchmarks, bidding decision trees, search term audit protocol. 42,000 words.

$5 on Gumroad →