Search code examples
stringpowershellfindstrselect-string

Powershell to Extract String after finding another string


I'm looking for a way to find a string in a file, then extract everything between that string and a separator. I can get the LINE out of the file, but I'm a little stumped on how to get the string I want out of it.

Line out of the file is this:

<add key="ConnectionString" value="Data Source=xxxxxx;Initial Catalog=Database;Integrated Security=True" />

I can find the "Data Source=", but I want to return "xxxxxx". Here's what I'm using:

((Get-Process -Name "db-engine").Path ) + '.Config' | Select-String -Path {$_} - Pattern 'Data Source='

This gives me the whole "add key" line from above.

Thanks in advance for any help!

EDIT: Thanks for the responses. After doing some more digging it looks like the "more proper" way is actually to use [xml] to pull the contents of the file into an xml object. Then I can grab values and use split to break the data up into the chunks I need. Final code will look something like this:

$configpath     = ((Get-Process -Name "db-engine").Path)
$linepath       = $configpath + ".Config"
[xml]$xmlfile   = get-content $linepath
$xmlvalue       = ($xmlfile.configuration.appSettings.add | where {$_.key -eq "ConnectionString"}).value
$server         = $xmlvalue.split(";=")[3]
$db             = $xmlvalue.split(";=")[5]  

Still working out the kinks, but this seems to get me on the right path. Split breaks the input into an array, so the [x] lets me call a particular element. With multiple delimiters in the split, it breaks the input at any of them. Maybe this can help someone else in the future.

Thanks for all the help, guys!


Solution

  • Personally, I'd just get the value of the attribute -- possibly with an XQuery with Select-Xml -- then split it on semicolons, and then use ConvertFrom-StringData:

    $xml = [xml]'<add key="ConnectionString" value="Data Source=xxxxxx;Initial Catalog=Database;Integrated Security=True" />';
    $ConnectionString = ($xml | Select-Xml -XPath '/add[@key="ConnectionString"]/@value').Node.'#text'
    $DataSource = ($ConnectionString.Split(';') | ConvertFrom-StringData).'Data Source'