2017-09-14 159 views
1

我正在学习PowerShell并希望匹配变量中的字符串。考虑这个例子:Select-String返回多行

$string = ipconfig 
Select-String -InputObject $string -Pattern '127.0.0.1' 

返回整个字符串。不只是'127.0.0.1'.所以我试过:

Select-String -InputObject $string -SimpleMatch '127.0.0.1' -AllMatches 

这也返回整个字符串。我究竟做错了什么?我只想看看比赛,而不是其他线路。

+1

'$ string |选择字符串'127.0.0.1''的帮助? – arco444

回答

0

Select-String返回一个.Matches属性,该属性是匹配的集合。那该.Value属性是相匹配的值:

$string = ipconfig 
(Select-String -InputObject $string -Pattern '127.0.0.1').Matches.Value 

这个例子会返回一个看起来像一个IP地址的所有值:

(Select-String -InputObject $string -Pattern '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' -AllMatches).Matches.Value 

请注意,如果你是匹配对准确的图谱(例如,没有通配符/正则表达式),那么你可以只使用-Quiet基于模式匹配是否返回真/假:

$MyString = '127.0.0.1' 
If (Select-String -InputObject $string -Pattern $MyString -Quiet) { $MyString } 

然后