Getting Database Connection String

by Jun 5, 2014

Have you ever been puzzled just what the connection string would look like for a given database? When you create a new data source in Control Panel, a wizard guides you through the creation process. Here is a way to utilize this wizard and get back the resulting connection string.

Note that the wizard choices depend on the installed database drivers on your machine.

function Get-ConnectionString
{
  
  $Path = Join-Path -Path $env:TEMP -ChildPath 'dummy.udl'
  
  $null = New-Item -Path $Path -ItemType File -Force
  
  $CommandArg = """$env:CommonProgramFiles\System\OLE DB\oledb32.dll"",OpenDSLFile "  + $Path 

  
  Start-Process -FilePath Rundll32.exe -Argument $CommandArg -Wait
  $ConnectionString = Get-Content -Path $Path | Select-Object -Last 1
  $ConnectionString | clip.exe
  Write-Warning 'Connection String is also available from clipboard'
  $ConnectionString

} 

When you call Get-ConnectionString, a dummy udl file is created and opened by the Control Panel wizard. You can then walk through the wizard. Once done, PowerShell examines the results in the dummy file and returns the connection string to you.

This is possible because Get-Process uses -Wait, effectively halting the script until the wizard exists. At that point, the script can safely examine the udl file.

Twitter This Tip! ReTweet this Tip!