String Powershell在找到另一个字符串后提取字符串

String Powershell在找到另一个字符串后提取字符串,string,powershell,findstr,select-string,String,Powershell,Findstr,Select String,我正在寻找一种在文件中查找字符串的方法,然后提取该字符串和分隔符之间的所有内容。我可以把线从文件中取出来,但我对如何从中取出来我想要的线有点困惑 文件外的行是: <add key="ConnectionString" value="Data Source=xxxxxx;Initial Catalog=Database;Integrated Security=True" /> 这给了我整个“添加关键点”行从上面 提前感谢您的帮助 编辑:谢谢你的回复。在进一步挖掘之后,看起来“更合适”

我正在寻找一种在文件中查找字符串的方法,然后提取该字符串和分隔符之间的所有内容。我可以把线从文件中取出来,但我对如何从中取出来我想要的线有点困惑

文件外的行是:

<add key="ConnectionString" value="Data Source=xxxxxx;Initial Catalog=Database;Integrated Security=True" />
这给了我整个“添加关键点”行从上面

提前感谢您的帮助

编辑:谢谢你的回复。在进一步挖掘之后,看起来“更合适”的方法实际上是使用[xml]将文件内容拉入xml对象。然后,我可以获取值并使用split将数据分解为所需的块。最终代码如下所示:

$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]  
仍在解决问题,但这似乎让我走上了正确的道路。Split将输入拆分为一个数组,因此[x]允许我调用特定的元素。如果拆分中有多个分隔符,则会在其中任何一个分隔符处中断输入。也许这可以在将来帮助其他人


谢谢你们的帮助,伙计们

就我个人而言,我只需要获取属性的值——可能是使用带有Select Xml的XQuery——然后将其拆分为分号,然后使用
convertfromStringData

$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'
$xml=[xml]'';
$ConnectionString=($xml | Select xml-XPath'/add[@key=“ConnectionString”]/@value').Node.#text'
$DataSource=($ConnectionString.Split(“;”)| ConvertFrom StringData)。“数据源”

就我个人而言,我只需要获取属性的值——可能使用带有Select Xml的XQuery——然后将其拆分为分号,然后使用
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'
$xml=[xml]'';
$ConnectionString=($xml | Select xml-XPath'/add[@key=“ConnectionString”]/@value').Node.#text'
$DataSource=($ConnectionString.Split(“;”)| ConvertFrom StringData)。“数据源”

<代码> > P>我同意@ BACON位——如果您有XML文件,那么您可能需要考虑这样对待它。如果要使用选择字符串,可以使用MatchInfo捕获的组。使用命名组的示例:

 gc .\dataSource.txt | Select-String -Pattern 'Data Source=(?<ds>.+?);' | % { $_.Matches[0].Groups['ds'].Value }
gc.\dataSource.txt |选择字符串模式“数据源=(?。+?);”|%{$\.Matches[0]。组['ds'].Value}

<代码> > P>我同意@ BACON位——如果您有XML文件,那么您可能需要考虑这样对待它。如果要使用选择字符串,可以使用MatchInfo捕获的组。使用命名组的示例:

 gc .\dataSource.txt | Select-String -Pattern 'Data Source=(?<ds>.+?);' | % { $_.Matches[0].Groups['ds'].Value }
gc.\dataSource.txt |选择字符串模式“数据源=(?。+?);”|%{$\.Matches[0]。组['ds'].Value}

我在解决方案中使用了其中的一些元素。我把它添加到编辑过的帖子中。谢谢我已经在我的解决方案中使用了其中的一些元素。我把它添加到编辑过的帖子中。谢谢这是一个有趣的方法。今后我会记住这一点。谢谢这是一个有趣的方法。今后我会记住这一点。谢谢