Check database connection using PowerShell and SQLCL
November 29, 2023Sometimes you want to check if a database is reachable before starting a command or a script. This PowerShell function can do the trick
<#
.SYNOPSIS
Check connection to a database
.DESCRIPTION
Check connection to a database using sqlcl prio to a script/command
make sure globale variables are set for:
$sqlcl_exe: C:\Sqldeveloper\sqlcl\sqlcl\bin
$sqlcl_log: c:\tmp\connection.log
$sqlcl_errorlog: c:\tmp\connection_errors.log
@$sqlcl_check_script : c:\Tools\connection_test.sql
containing:
SET HEADING OFF
SET SQLFORMAT csv
select 'connection_ok' from dual;
exit;
.PARAMETER owner
Run script as
.PARAMETER password
Password of the user
.PARAMETER database
Database to check connection for
.EXAMPLE
PS C:\> CheckConnection -owner "user1" -password "password" -database "db1"
.NOTES
You can store the call of this function to for instance $conn_value
$conn_value can now be checked: 0 = Connection successfull, other = Connection failed
#>
function CheckConnection
{
[CmdletBinding()]
[Alias()]
[OutputType([int])]
param
(
[Parameter(Mandatory = $true,
ValueFromPipelineByPropertyName = $true)]
$owner,
$password,
$database
)
$connect_string = $owner + "/" + "$password" + "@" + $database
if ($owner -eq 'sys')
{
$myarg = "-s $owner/\`"$password\`"@$database as sysdba @$sqlcl_check_script"
}
else
{
$myarg = "-s $owner/\`"$password\`"@$database @$sqlcl_check_script"
}
Clear-Content -Path $sqlcl_log
Clear-Content -Path $sqlcl_errorlog
try
{
start-Process -FilePath $sqlcl_exe -ArgumentList $myarg -RedirectStandardOutput $sqlcl_log -RedirectStandardError $sqlcl_errorlog -Wait -WindowStyle Hidden
}
catch
{
[System.Windows.MessageBox]::Show("Starting sqlcl failed! $error", "Starting sqlcl failed!", 'OK', 'Error')
}
$conn_errors = $(Get-Content -Path $sqlcl_log | Select-String -Pattern "ORA-" -AllMatches).count
if ($conn_errors -eq 0)
{
return 0
}
else
{
[System.Windows.Forms.MessageBox]::Show("Failed to connect to $database!$sqlOutput", "Failed to connect to $database!", 0, "Error")
return 99
}
}