Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a web.config connection string

I just started on PowerShell and I am trying to split a connection string that is saved as a string. I have attempted regex and array splits but since I am learning I am looking for an entry level idea.

Below is a connection string example I am trying to split with each of the key areas being assigned to a variable.

@{connectionString=Data Source=database;Initial Catalog=catalog;User ID=userid;Password=password}

I would ideally like each of the values made available to a variable.

like image 363
Hopeless Programmer Avatar asked Nov 29 '25 00:11

Hopeless Programmer


2 Answers

Rather than manually parsing the connection string, you can use SqlConnectionStringbuilder.

$builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder -argumentlist "Data Source=database;Initial Catalog=catalog;User ID=userid;Password=password";
$builder["User Id"];
$builder["Data Source"];
$builder["Initial Catalog"];
like image 114
alroc Avatar answered Nov 30 '25 16:11

alroc


For simplicity, I removed the @{ and } from the string. I'm sure you can do some pre-processing to the string to trim these out.

$string = "connectionString=Data Source=database;Initial Catalog=catalog;User ID=userid;Password=password"
$res = $string.Split(";")
$connString = $res[0]
$initialCatalog = $res[1]
$userId = $res[2]
$password = $res[3]
like image 32
Maria Ines Parnisari Avatar answered Nov 30 '25 16:11

Maria Ines Parnisari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!