在我有的文件中
datasource =(Description=(failover=on)(load_balance=off) transport_connect_timeout=1)
我想使用$datasource
传递值。 当我使用
$datasource =Get-content "c:file | select-string -pattern datasource"
这给了我整条线
datasource =(Description=(failover=on)(load_balance=off)transport_connect_timeout=1)
但我只需要
(Description=(failover=on)(load_balance=off) transport_connect_timeout=1)
请帮助我。提前谢谢。
这里有一种方法:
$fullValue = "datasource =(Description=(failover=on)(load_balance=off) transport_connect_timeout=1)"
($fullValue -split "=" | Select-Object -Skip 1) -join "="
- 在等号上拆分字符串
- 抓取除第一个拆分字符串之外的所有字符串
- 使用等号将它们重新连接在一起
Select-String 使用带有 -Pattern 的正则表达式。
我会使用更高级的,后面有一个积极的外观和一个捕获组。
$datasource = sls .file.txt -Patt '(?<=datasource =)(.*)$'|% {$_.Matches.groups[1].value}
来自 regex101.com 的正则表达式解释
(?<=datasource =)(.*)$
Positive Lookbehind (?<=datasource =)
Assert that the Regex below matches
datasource = matches the characters datasource = literally (case sensitive)
1st Capturing Group (.*)
.*
. matches any character (except for line terminators)
* Quantifier — Matches between zero and unlimited times,
as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line
要% {$_.Matches.groups[1].value}
的管道循环访问所有匹配项,并仅返回捕获组的内容 [1]