| Lesson 4 | Creating backup scripts |
| Objective | Create a backup script in Oracle AI Database 26ai. |
A useful backup script does more than save typing. It makes the intended operation repeatable, produces evidence you can inspect, and gives a scheduler a clear success or failure result. In this lesson you will create an RMAN command file, run it with a selected target connection and log, and compare it with a script stored in a recovery catalog. Start with a lab database and reviewed settings before adapting the examples to production.
The target database is the database RMAN backs up or restores. A recovery catalog holds backup metadata and optionally stored scripts; the physical backup pieces reside in backup storage. The previous lesson prepared the catalog and registered a target. Registration is a prerequisite for that catalog workflow, but it does not itself create a backup. This lesson supplies the commands that perform the backup.
You can organize the work in three parts. An RMAN command file is plain text on the client filesystem and can be used with or without a catalog. A stored script resides in the recovery catalog and is executed through an RMAN session connected to the catalog. An operating system wrapper, such as a PowerShell script, selects the executable, connection, command file, log location, and exit-code handling. A scheduler starts that wrapper at the agreed time.
For the first implementation, keep the backup commands in one small command file. Put machine-specific paths and monitoring in the wrapper. Record persistent database configuration separately. This division makes review easier: a change to the backup content should not require searching through scheduler configuration, and a change to the log directory should not alter the backup policy.
Use meaningful names such as daily_full.rman and keep an approved version with your operational documentation. The extension is a naming convention, not a different RMAN language. Save plain text without Markdown fences, HTML tags, console prompts, or numbered continuation prompts copied from an interactive transcript.
Before running anything, identify the expected target name, DBID, service, and container. These examples back up a complete multitenant container database by connecting to its root. A connection to an individual PDB changes the available scope; it is not interchangeable with a root connection. Use the matching supported RMAN client and an operator with the appropriate backup administration privilege. Oracle documents connection scope and SYSBACKUP in the CONNECT reference.
The online backup example assumes ARCHIVELOG mode, an open or mounted target with a current control file, and usable disk backup storage. A NOARCHIVELOG database requires a different, consistent shutdown and mounted-backup procedure. Do not add shutdown commands to this online script to make an unsuitable environment appear to fit it.
Distinguish two locations. RMAN reads a command file and writes its message log on the client where the executable runs. Database server sessions write disk backup pieces to paths accessible from the server. If your Windows client connects to a Linux database server, a Windows script path does not become a Linux backup destination. The configured channels and storage must match the target's server environment.
Agree on enough space for database backups, archived logs, control file autobackups, and the retention period. Confirm which account can write the backup destination and which account can read the command file and write client logs. Make directories and permissions part of the deployment checklist rather than expecting RMAN to create every missing directory.
In a verified interactive session, inspect the current settings and enable control file autobackups if that is the approved configuration:
SHOW ALL;
CONFIGURE CONTROLFILE AUTOBACKUP ON;
SHOW CONTROLFILE AUTOBACKUP;
These are RMAN commands. Run configuration changes during setup and review their effect; a routine daily file should not silently reset retention, encryption, or channel settings. Control file autobackups support recovery when the main repository is unavailable and include the server parameter file when the database uses one. Preserve the information needed to locate and restore them outside the database being protected. See Configuring the RMAN Environment.
The sample requests disk backups and uses the site's configured destination. Confirm that destination before execution. An appropriate fast recovery area or channel format can supply it. The next lesson examines FORMAT in detail; a beginner script does not need a guessed filesystem path simply to demonstrate a backup.
Save the following as C:\rman\scripts\daily_full.rman on the Windows client. The connection will be supplied when starting RMAN, so the file contains no login statement or password:
# Full database backup and archived redo logs.
BACKUP AS BACKUPSET
DEVICE TYPE DISK
TAG 'DAILY_FULL'
DATABASE PLUS ARCHIVELOG;
LIST BACKUP SUMMARY;
EXIT;
This produces backup sets for the database and archived redo logs. The tag labels the operation's backups for later identification. Reusing a tag does not give each run a unique identity, select a retention period, or overwrite an earlier backup merely because the label matches. Identify a particular job using its timestamp, log, and recorded backup pieces.
PLUS ARCHIVELOG includes archived redo around the database backup so recovery has the necessary redo coverage. In a CDB, this operation requires the root connection. It does not mean that the live online redo log files are copied as ordinary backup pieces. Oracle's BACKUP reference describes the scope and prerequisites.
This is a full backup, not an incremental level 0 baseline. A level 0 backup participates in an incremental strategy; a normal full backup does not serve the same role for subsequent level 1 backups. Choose an incremental design deliberately when the recovery plan calls for it, and document the baseline and incremental schedule together.
The starter file keeps archived logs and existing backups. Adding deletion is a separate policy decision. It also avoids manually allocating a channel because the reviewed automatic disk configuration can supply one. Manual allocation belongs in a RUN block when you need explicit session channel control; it is not a requirement for every basic disk backup.
From PowerShell, invoke the intended RMAN executable in syntax-check mode. Replace the Oracle home path with the installation you actually use:
$rmanExe = 'C:\Oracle\product\26ai\dbhome_1\bin\rman.exe'
& $rmanExe CHECKSYNTAX `
'CMDFILE=C:\rman\scripts\daily_full.rman' `
'LOG=C:\rman\logs\daily_full_syntax.log'
$syntaxExitCode = $LASTEXITCODE
The PowerShell backtick continues the command onto the next line; do not put spaces after it. The call operator & runs the executable named by the variable. Check the result and the syntax log. RMAN's CHECKSYNTAX parses the commands without performing the backup, as described in the RMAN command-line reference.
A successful syntax check establishes only that the client recognizes the command language. It does not test login privileges, the target's state, storage access, free space, media-manager configuration, or the ability to restore a backup. A syntactically valid script can still fail at runtime. Keep syntax checking as the first verification stage, not the final acceptance criterion.
For a local lab target, operating system authentication can avoid a password in the script. The following wrapper assumes the correct Oracle environment and a Windows account authorized for the slash connection. That connection uses SYSDBA by default; where the account is configured for operating system SYSBACKUP authentication, supply '/ AS SYSBACKUP' as the target connection instead.
$rmanExe = 'C:\Oracle\product\26ai\dbhome_1\bin\rman.exe'
$scriptFile = 'C:\rman\scripts\daily_full.rman'
$runStamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$logFile = "C:\rman\logs\daily_full_$runStamp.log"
& $rmanExe TARGET / NOCATALOG `
"CMDFILE=$scriptFile" "LOG=$logFile"
$rmanExitCode = $LASTEXITCODE
if ($rmanExitCode -ne 0) {
throw "RMAN failed with exit code $rmanExitCode. Review $logFile"
}
Prepare the script and log directories beforehand. The selected executable, ORACLE_SID, Oracle home, and job identity must identify the intended local database. Verify the target's name and DBID in the resulting log. An explicit executable path reduces reliance on whichever RMAN happens to be first on the shell's search path.
CMDFILE reads and executes the file; LOG records its commands and output. The timestamp preserves separate job evidence. Capture $LASTEXITCODE immediately after the native executable so a later command cannot replace the result. Microsoft describes this variable in PowerShell automatic variables. Ensure the surrounding job reports failures to the scheduler or monitoring system rather than merely printing them.
NOCATALOG intentionally uses the target control file repository for this example. A catalog is optional for the command-file method. This invocation does not test connectivity to the catalog created in Lesson 3. Windows changes the shell syntax, environment, and paths; it does not introduce a different grammar for RMAN's BACKUP command.
For a supervised catalog-assisted lab run, start a fresh RMAN session and establish both connections before running repository operations:
rman
RMAN> CONNECT TARGET "c##backup_admin@prod AS SYSBACKUP";
RMAN> CONNECT CATALOG rco@catdb;
RMAN> @'C:\rman\scripts\daily_full.rman'
Here, prod is the target root service and catdb is the catalog service. The common target operator and catalog owner already exist with appropriate privileges. Enter passwords at their prompts. The file's EXIT; ends this session when reached. The @ form reads a client command file; for scheduled work, prefer a startup invocation with an explicit command file and log.
Do not first run a backup in default NOCATALOG mode and then attempt to attach a catalog within that same session. Start a new session and establish the intended repository connection before the backup. For unattended catalog jobs, configure approved authentication that works under the job identity without a password prompt. A copied interactive connection string containing a password is not an acceptable scheduling design.
With the intended registered target and recovery catalog connected, create a local script containing the backup command:
CREATE SCRIPT daily_full
COMMENT 'Full database and archived redo backup to disk'
{
BACKUP AS BACKUPSET
DEVICE TYPE DISK
TAG 'DAILY_FULL'
DATABASE PLUS ARCHIVELOG;
}
PRINT SCRIPT daily_full;
RUN { EXECUTE SCRIPT daily_full; }
A local stored script belongs to the connected target. A global stored script can be shared across registered targets, so shared names and assumptions need careful review. The stored body contains commands allowed inside a RUN block; do not include another RUN, client connection statements, or EXIT in it. Keep those session controls outside the stored backup body. See CREATE SCRIPT and EXECUTE SCRIPT.
Inspect an existing script before changing it. Use the supported replacement procedure when its definition needs revision and record the approved change. Export a readable copy for review and recovery documentation:
PRINT SCRIPT daily_full
TO FILE 'C:\rman\scripts\daily_full_stored_export.rman';
This writes on the RMAN client's filesystem. Keep the export alongside the operational documentation instead of depending on catalog availability to read the procedure during an outage. Oracle's PRINT SCRIPT reference explains file output.
Ordinary catalog-connected RMAN operations synchronize relevant metadata. When you need a deliberate refresh with both connections established, use RESYNC CATALOG;. The command has no TARGET my_database suffix in this procedure. Resynchronization updates repository metadata; it neither copies backup payloads nor automatically mirrors independent catalog databases. See RESYNC CATALOG.
Protect the catalog hosting database with its own tested backup plan, as discussed in the previous lesson. Keep its recovery instructions available separately. Two catalogs do not by themselves demonstrate independent protection; their hosts, storage, credentials, and recovery dependencies can still share failure points. Registering a target and creating a stored script do not remove that operational responsibility.
Review the first runtime log for the expected target identity, completed backup commands, piece locations, control file autobackup, elapsed time, and errors. Confirm that the expected records appear in LIST BACKUP SUMMARY;. A summary row is evidence of repository history, not proof that storage remains accessible indefinitely. Retain the script version and job log with the run's result.
BACKUP VALIDATE checks source files without creating a backup. RESTORE ... VALIDATE checks selected backup content without restoring datafiles. These checks help diagnose different problems, but neither is a replacement for a recovery exercise that verifies the full restore and recovery process. Oracle describes validation in VALIDATE and RESTORE.
Review retention through REPORT OBSOLETE; before introducing cleanup. Archived log deletion must also account for the configured deletion policy and any standby requirements. CROSSCHECK updates recorded availability, while DELETE EXPIRED removes expired records; that differs from deleting obsolete physical backups. In a command file, deletion commands do not rely on an interactive confirmation prompt. Read the DELETE reference before adding maintenance to a scheduled file.
If a job fails before writing an RMAN log, first inspect the wrapper's executable path, command-file path, and log-directory permissions. A scheduler message saying that it launched PowerShell does not show that RMAN started successfully. Retain the wrapper output as well as the RMAN log so the earliest failure remains visible.
If RMAN starts but cannot connect, check the selected Oracle environment, service resolution, and job identity. If it connects but a channel cannot create a backup piece, investigate the database server's destination and permissions. Repeatedly changing the client log directory will not repair a server storage error. If the backup succeeds but catalog synchronization fails, record both outcomes and resolve the catalog error instead of labeling the entire recovery plan verified.
After a partially completed backup, inspect the pieces and repository records before retrying. Some work may have completed before the error. Do not delete those pieces as a reflex, and do not assume that rerunning a file containing maintenance commands has the same consequences as rerunning this backup-only starter file. Keep a short incident note identifying the script version, target, time, error, and corrective action.
Finally, schedule the tested wrapper through Windows Task Scheduler or the site's established scheduler. Specify the executable, working environment, job account, log directory, overlap policy, and failure notification. Test under that account because your interactive desktop environment may differ. Protect wallets, password and network configuration, external data, and installation dependencies separately; RMAN does not back up every file needed to rebuild the environment.