Skip to content

Commit

Permalink
Implement a script to automatically create odbcad configs.
Browse files Browse the repository at this point in the history
  • Loading branch information
stevewgr committed May 22, 2024
1 parent bb7c474 commit 9d9952a
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions odbcad.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# If you invoke the script from the terminal, you can specify the server and db name in case you changed it.
# Otherwise just stick to the default values.
param (
# change server_name if you installed your sql server as a Named Instance.
# If you installed on the Default Instance, then you can leave this as-is.
# If you're still not sure what is your sql server names, you can run the following powershell command:
# (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
[string][Parameter(Mandatory = $false)]
$server_name = "localhost",

[string][Parameter(Mandatory = $false)]
$db_name = "kodb",

[switch][Parameter(Mandatory = $false)]
$quiet
)


. "$PSScriptRoot\logger.ps1"

function Main {
$drivers = Get-OdbcDriver | Where-Object { $_.Name -like "*SQL Server*" -and $_.Platform -eq "32-bit" }
if (!$drivers) {
MessageWarn "Are you sure SQL Server is installed? I couldn't find any drivers."
exit 1
}

$selected_driver = $null
if ($drivers.Count -eq 1) {
$selected_driver = $drivers[0]
} else {
while (-not $selected_driver) {
MessageInfo "Select the desired SQL Driver:"
for ($i = 0; $i -lt $drivers.Count; $i++) {
Message "$($i+1). $($drivers[$i].Name)"
}

$user_input = -1
$input_valid = [int]::TryParse((Read-Host "Enter the number of the driver you want to select"), [ref]$user_input)
if (-not $input_valid -or $user_input -lt 1 -or $user_input -gt $drivers.Count) {
MessageWarn "Invalid selection.`n"
} else {
$selected_driver = $drivers[$user_input - 1]
MessageInfo "Selected SQL Driver: $($selected_driver.Name)`n"
break
}
}
}

Remove-OdbcDsn -Name $db_name -DsnType "User" -ErrorAction Ignore
Add-OdbcDsn -Name $db_name -DriverName $selected_driver.Name -DsnType "User" -SetPropertyValue @("Server=$server_name", "Database=$db_name", "AutoTranslate=No", "Trusted_Connection=Yes")

# Test connection
$con = New-Object System.Data.Odbc.OdbcConnection
$con.ConnectionString = "DSN=$db_name"
$con.Open()
$is_successful = $con.State -eq "Open"
$con.Close()
if ($is_successful) {
MessageSuccess "Successfully created odbcad connection driver and tested connection!"
} else {
MessageError "Failed to test connection. Check that you first imported the database."
MessageError "If that didn't work, depending on how you installed MSSQL (Default or Named Instance), you may need to change the server above from localhost to yours."
exit 1
}
}

Main
if (-not $quiet) {
cmd /c 'pause'
}

0 comments on commit 9d9952a

Please sign in to comment.