12

For some reason I'm having a brutal time parsing the connection string in the web.config file.

I've already gotten connectionString but I'm trying to get all the values such as the

  • Data Source
  • Initial Catalog
  • Username
  • etc...

The connection string looks like:

Data Source=db.sample.com;user id=sample-user;password=sample-password;Initial Catalog=sample-catalog;

1
  • 1
    Do you need to use a regex? It looks like two calls to whatever Powershell uses for splitting strings would do the trick. One call to split on ;, then loop through the results and split by = to get your key/value pairs. I'd put this as an answer but I don't know a) if Powershell has a split function, and b) what it's called. Commented Sep 30, 2011 at 18:29

1 Answer 1

24

Use System.Data.Common.DbConnectionStringBuilder

$sb = New-Object System.Data.Common.DbConnectionStringBuilder

# Attempting to set the ConnectionString property directly won't work, see below
$sb.set_ConnectionString('Data Source=db.sample.com;user id=sample-user;password=sample-password;Initial Catalog=sample-catalog;')

$sb

Output:

Key             Value          
---             -----          
data source     db.sample.com  
user id         sample-user    
password        sample-password
initial catalog sample-catalog 

See also for more details: DbConnectionStringBuilder does not parse when used in PowerShell

(That is why this funny syntax $sb.set_ConnectionString(...) is used instead of $sb.ConnectionString = ...).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this! Using .Net DbConnectionStringBuilder in a PowerShell script is really the best option of getting parts extracted the right way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.