You can search for those different strings like below:
# read the text as single multiline string
$text = Get-Content -Path 'X:\Somewhere\yourfile.txt' -Raw
# create a regex string with placeholder {0}
$regex = '(?m)^& data df put king/man/{0}\s+(".+")'
# clear some variables
$connString = $connStringLog = $ConnStringSession = $null
$connString = if ($text -match ($regex -f 'ConnString')) {
$matches[1] # --> "Connection data 1"
}
$connStringLog = if ($text -match ($regex -f 'ConnStringLog')) {
$matches[1] # --> "Connection Log data"
}
$ConnStringSession = if ($text -match ($regex -f 'ConnStringSession')) {
$matches[1] # --> "Conn String data"
}
Or use regex -replace
:
# read the text as single multiline string
$text = Get-Content -Path 'X:\Somewhere\yourfile.txt' -Raw
# create a regex string with placeholder {0}
$regex = '(?sm).*^& data df put king/man/{0}\s+("[^"]+").*'
$connString = $text -replace ($regex -f 'ConnString'), '$1'
$connStringLog = $text -replace ($regex -f 'ConnStringLog'), '$1'
$ConnStringSession = $text -replace ($regex -f 'ConnStringSession'), '$1'
$connString # --> "Connection data 1"
$connStringLog # --> "Connection Log data"
$ConnStringSession # --> "Conn String data"
P.S. If you also need the search to be case-sensitive, then change -match
into -cmatch
in the first code and -replace
into -creplace
for the second code
As per your comment the wanted data may or may not be quoted as in your example lines, then change the regex creation in the first code block into
$regex = '(?m)^& data df put king/man/{0}\s+(.+)'
Basically remove the quotes in the regex
As alternative, here's another approach using switch
(line-by-line):
# clear some variables
$connString = $connStringLog = $ConnStringSession = $null
switch -Regex -File 'X:\Somewhere\yourfile.txt' {
'^& data df put king/man/ConnString\s+(.+)$' { $connString = $matches[1] }
'^& data df put king/man/ConnStringLog\s+(.+)$' { $connStringLog = $matches[1] }
'^& data df put king/man/ConnStringSession\s+(.+)$' { $ConnStringSession = $matches[1] }
}
$connString # --> Connection data 1
$connStringLog # --> Connection Log data
$ConnStringSession # --> Conn String data