1.Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass # --- CONFIGURATION --- $oracleHome = "D:\automation\WINDOWS.X64_193000_db_home" $patchDir = "D:\automation\p37532350_190000_MSWIN-x86-64 (2)\37532350" $opatchDir = "$oracleHome\OPatch" $opatchZip = "D:\automation\p6880880_190000_MSWIN-x86-64.zip" $logFile = "C:\Users\Administrator\Documents\oracle_patch_log.txt"

# Define Oracle services
$dbService = “OracleServiceORCL”
$otherServices = @(
“OracleServiceORCL”, # Included here too, but the script handles it first via $dbService
“OracleOraDB19Home1TNSListener”,
“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 Oracle DB service: $dbService …”
Stop-Service -Name $dbService -Force -ErrorAction SilentlyContinue
Write-Host “Stopping other Oracle services…”
foreach ($svc in $otherServices) {
if ($svc -ne $dbService) {
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) {
if ($svc -ne $dbService) {
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
