ps/Modules/Alkami.PowerShell.Database/Public/Confirm-DatabaseAccess.ps1
2023-05-30 22:51:22 -07:00

75 lines
2.5 KiB
PowerShell

function Confirm-DatabaseAccess {
<#
.SYNOPSIS
This function confirms that the user running this script has access to the requested connection string.
.DESCRIPTION
This function confirms that the user running this script has access to the requested connection string.
It uses the credentials of the connection string to connect.
.PARAMETER ConnectionString
Used to test connection to the server. If not supplied, the AlkamiMaster from the machine.config is used, if available
.PARAMETER ConnectionTimeout
SQL Connection Timeout in Seconds. Defaults to 15.
.INPUTS
Connection string to connect to the server
.OUTPUTS
Boolean state based on whether or not the connection attempt was successful.
.EXAMPLE
Confirm-DatabaseAccess
Confirm-DatabaseAccess
#>
[CmdletBinding()]
[OutputType([System.Boolean])]
param(
[Parameter(Mandatory = $false, Position = 0)]
[string]$ConnectionString,
[Parameter(Mandatory = $false, Position = 1)]
[int]$ConnectionTimeout = 15
)
process {
$logLead = (Get-LogLeadName)
try {
if ([string]::IsNullOrEmpty($connectionString)) {
## If there is no passed in connection string, use the current computer connection string
Write-Verbose "$logLead : Attempting to Retrieve Connection String from the machine.config"
$connectionString = (Get-ConnectionString 'AlkamiMaster')
}
Write-Verbose "$logLead : Creating a ConnectionStringBuilder Object from the connection string"
$conStrBuilder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder "$($connectionString.ToString())"
$safeConnectionString = New-Object System.Data.SqlClient.SqlConnectionStringBuilder "$($connectionString.ToString())"
$conStrBuilder['Connection Timeout'] = $ConnectionTimeout
$safeConnectionString['Connection Timeout'] = $ConnectionTimeout
if (-not (Test-StringIsNullOrEmpty -Value $safeConnectionString.Password)) {
$safeConnectionString.Password = "Redacted"
}
Write-Verbose "$logLead : Testing Connection Using ConnectionString: $($safeConnectionString.ToString())"
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $conStrBuilder.ToString()
$sqlConnection.Open()
$sqlConnection.Close()
Write-Verbose "$logLead : Was able to connect to $connectionString"
return $true
} catch {
Write-Warning "$logLead : Can not connect to the specified database. Do you have approved access to the server?"
return $false
} finally {
if ($null -ne $sqlConnection) {
$sqlConnection.Dispose()
}
}
}
}