Skip to main content

⚡ Automating Oracle 19c Database Patching on Windows Server with PowerShell

Applying Oracle patches on Windows often feels repetitive and error-prone — stopping services, updating OPatch, applying patches, running datapatch, and restarting services.

To save time ⏱ and reduce mistakes ⚠, I created a PowerShell automation script that performs the patching process end-to-end 🚀.


🔹 Why Automate Oracle Patching?

  • ⏱ Save time by automating repetitive steps

  • ⚙ Avoid manual errors during patching

  • 📜 Maintain logs for auditing and troubleshooting

  • 🛡 Ensure consistent, reliable patching


🔹 Full PowerShell Script

# --- CONFIGURATION --- $oracleHome = "c:\users\administrator\downloads\v982656-01" # Change if this is not your actual Oracle Home! $patchDir = "C:\Users\Administrator\Downloads\p37962957_190000_MSWIN-x86-64\37962957" #update the Patchfile directory $opatchDir = "$oracleHome\OPatch" $opatchZip = "C:\Users\Administrator\Downloads\p6880880_190000_MSWIN-x86-64.zip" #Based on your setup update Opatch directory $logFile = "C:\Users\Administrator\Documents\oracle_patch_log.txt" #Output logfile generation location # Define services $dbService = "OracleServiceORCL" $otherServices = @( "OracleOraDB19Home1TNSListener", "OracleOraDB19Home1MTSRecoveryService", "OracleRemExecServiceV2", "OracleVssWriterORCL" ) Start-Transcript -Path $logFile -Append # --- FUNCTIONS --- function Ensure-Opatch { if (-Not (Test-Path $opatchZip)) { Write-Host "OPatch ZIP not found at $opatchZip. Please download it first." Stop-Transcript exit 1 } if (Test-Path $opatchDir) { $backupDir = "$oracleHome\OPatch_backup_$(Get-Date -Format 'yyyyMMdd_HHmmss')" Write-Host "Backing up existing OPatch directory to $backupDir ..." Rename-Item -Path $opatchDir -NewName $backupDir -Force } Write-Host "Extracting new OPatch from $opatchZip to $oracleHome ..." Expand-Archive -Path $opatchZip -DestinationPath $oracleHome -Force if (-Not (Test-Path "$opatchDir\opatch.bat")) { Write-Host "Failed to extract OPatch correctly. Exiting." Stop-Transcript exit 1 } Write-Host "OPatch replaced successfully." } function Stop-OracleServices { Write-Host "Stopping all Oracle services..." Stop-Service -Name $dbService -Force -ErrorAction SilentlyContinue foreach ($svc in $otherServices) { Stop-Service -Name $svc -Force -ErrorAction SilentlyContinue } Start-Sleep -Seconds 10 } function Start-DbService { Write-Host "Starting database service ($dbService)..." Start-Service -Name $dbService Start-Sleep -Seconds 10 } function Start-OtherServices { Write-Host "Starting remaining Oracle services..." foreach ($svc in $otherServices) { Write-Host "Starting $svc ..." Start-Service -Name $svc -ErrorAction SilentlyContinue } Start-Sleep -Seconds 10 } function Apply-Patch { Write-Host "Applying patch from $patchDir ..." Push-Location $patchDir & "$opatchDir\opatch.bat" apply -silent -oh $oracleHome $exitCode = $LASTEXITCODE Pop-Location if ($exitCode -ne 0) { Write-Host "Patch apply failed with exit code $exitCode. Exiting." Stop-Transcript exit 1 } } function Run-Datapatch { Write-Host "Running datapatch..." & "$oracleHome\OPatch\datapatch.bat" -verbose } # --- MAIN SCRIPT --- Write-Host "=== Oracle 19c Patch Automation Script ===" # Set environment variables $env:ORACLE_HOME = $oracleHome $env:PATH = "$oracleHome\OPatch;$env:PATH" Ensure-Opatch Stop-OracleServices Apply-Patch Start-DbService Run-Datapatch Start-OtherServices Write-Host "=== Patching complete. ===" Stop-Transcript

🔹 Breakdown of the Script

Here’s what each part of the script does:

1️⃣ Ensure-Opatch

  • Checks if the OPatch ZIP exists

  • Backs up the existing OPatch folder

  • Extracts the new OPatch utility

2️⃣ Stop-OracleServices

  • Stops the main database service (OracleServiceORCL)

  • Stops all dependent Oracle services (Listener, MTS Recovery, VSS Writer, etc.)

3️⃣ Apply-Patch

  • Navigates to the patch directory

  • Executes opatch apply -silent to apply the patch

  • Validates the exit code to ensure patching succeeded

4️⃣ Start-DbService

  • Starts only the database service

  • Keeps the instance running so that datapatch can be executed

5️⃣ Run-Datapatch

  • Runs datapatch.bat to update the Oracle data dictionary

  • Ensures the database registry is updated with the patch

6️⃣ Start-OtherServices

  • Restarts the remaining Oracle services

  • Brings the environment back online fully

7️⃣ Logging (Transcript)

  • Every action is logged to oracle_patch_log.txt for auditing and troubleshooting


🔹 How to Create the Script

  1. Open Notepad or any text editor

  2. Paste the entire script above

  3. Save the file as:

    oracle19c_patch.ps1
  4. Place the script in a convenient directory (e.g., C:\patches\scripts\)


🔹 How to Run the Script

  1. 📂 Extract your Oracle Patch ZIP to a directory

  2. 📦 Place the latest OPatch ZIP in the specified location

  3. 🖥 Open PowerShell as Administrator

  4. Navigate to the script location:

    cd C:\patches\scripts\
  5. Run the script with execution policy bypass:

    powershell -ExecutionPolicy Bypass -File .\oracle19c_patch.ps1
  6. 📜 Monitor the console output and check logs at:

    C:\Users\Administrator\Documents\oracle_patch_log.txt

🔹 Troubleshooting

  • Files in use → Make sure all Oracle services are stopped before running patch

  • 🔒 Datapatch lock errors → Check registry locks (refer Oracle MOS Note 1609718.1)

  • 📖 Patch failed → Review OPatch logs and the generated transcript file


⚠ Disclaimer

This script is provided as-is.
✔ Always test in a non-production environment before applying in production.
✔ Ensure you have valid backups before patching.



Comments

Popular posts from this blog

🚀 Automating Oracle Database Patching with Ansible: A Complete Guide

Oracle database patching has long been the bane of DBAs everywhere. It's a critical task that requires precision, expertise, and often results in extended maintenance windows. What if I told you that you could automate this entire process, reducing both risk and downtime while ensuring consistency across your Oracle estate? 💡 In this comprehensive guide, I'll walk you through a production-ready Ansible playbook that completely automates Oracle patch application using OPatch. Whether you're managing a single Oracle instance or hundreds of databases across your enterprise, this solution will transform your patch management strategy! 🎯 🔥 The Challenge: Why Oracle Patching is Complex Before diving into the solution, let's understand why Oracle patching is so challenging: 🔗 Multiple dependencies : OPatch versions, Oracle Home configurations, running processes ⚠️ Risk of corruption : Incorrect patch application can render databases unusable ⏰ Downtime requirements : Da...

Oracle RAC Switchover & Switchback: Step-by-Step Guide

 Ensuring business continuity requires regular Disaster Recovery (DR) drills. This guide covers the Switchover and Switchback process between Primary (DC) and Standby (DR) databases . Pre-checks Before Performing Switchover Before starting the activity, ensure there are no active sessions in the database. If any are found, share the session details with the application team, get their confirmation, and terminate the sessions. Primary Database Name: PRIMARY Standby Database Name: STANDBY  Identify Active Sessions set lines 999 pages 999 col machine for a30 col username for a30 col program for a30 compute sum of count on report break on report select inst_id,username,osuser,machine,program,status,count(1) "count" from gv$session where inst_id=1 and program like 'JDBC%' group by inst_id,username,osuser,machine,program,status order by 1,2; select inst_id,username,osuser,machine,program,status,count(1) "count" from gv$session where inst_id=2 and program lik...

Mastering Oracle RAC with SRVCTL Commands

Oracle Real Application Clusters (RAC) provide high availability, scalability, and manageability for databases. One of the most powerful tools for managing RAC databases is srvctl , a command-line utility that allows administrators to control various database services. This blog explores essential srvctl commands to help you efficiently manage Oracle RAC environments. 1. Checking Database Configuration and Status  List all available databases on the host:                  srvctl config database   Check the status of a specific database and its instances:                    srvctl status database -d <database_name>   Retrieve detailed status information about a database, including its instances and states:                    srvctl status database -d <database_name> -v 2. Stopping and Starting Databases   ...