I need PowerShell to run multiple Oracle SQL scripts from a folder. I am using below code, the foreach
loop is not working. It always executes the first script and exit. I have tried using for
loop instead of foreach
, it also doesn’t work. After the Invoke
statement it is not returning to the foreach
line.
# Get list of script files in the folder sorted by name in ascending order
$scriptFiles = Get-ChildItem -Path $scriptFolder -Filter "*.sql" | Sort-Object -Property Name
# Loop through each script file and execute it
foreach ($scriptFile in $scriptFiles) {
try {
# Construct the full path to the script file
$scriptPath = $scriptFile.FullName
Write-Host "Script file path: '$scriptPath'"
# Check if the script content is not empty
if (-not [string]::IsNullOrWhiteSpace($scriptPath)) {
# Construct the sqlplus command to execute the current script file
$sqlplusCommand = "sqlplus"
$arguments = "$oracleUser/$oraclePassword@$oracleDatabase '@$scriptPath'"
# Execute the SQL*Plus command using Invoke-Expression
Invoke-Expression "$sqlplusCommand $arguments"
Write-Host "Script '$scriptFile' executed successfully."
} else {
Write-Host "Script '$scriptFile' is empty. Skipping execution."
}
} catch {
Write-Host "Error executing script '$scriptFile': $_"
}
}`
New contributor
Debaparna Bandyopadhyay is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.