使用-Match
会为我提供True
/ False
个值,而不是文本行。
Get-Content ("\\path”) -tail 10 -wait | % {
foreach ($data in ($_ -match "Execute")) {
$First = $data.Substring(26,37).Trim()
Write-Host $First
}
}
我使用下面没有-tail -wait
的代码来执行我的操作,但我无法使用-tail
Get-Content
更改为解析文件。
$DB = Get-Content ("\\path”) -tail -ReadCount 5000000 | foreach { $_ -match "string to match" } | foreach{ $_.Trim()}
foreach ($Data in $DB) {
$First = $Data.Substring(26,37).Trim()
$Second = $Data
Write-Host $First
Write-Host $Second
}
答案 0 :(得分:1)
As a workaround, you can array-cast your $_
, like this:
foreach ($data in (,$_ -match "Execute")) {
Here's the output difference:
$data=@("bla bla","foo bla","foo bar","bla bar")
PS > $data | % { foreach ($a in ($_ -match "bla")){$a}}
True
True
False
True
PS > $data | % { foreach ($a in (,$_ -match "bla")){$a}}
bla bla
foo bla
bla bar
答案 1 :(得分:0)
嗯,db.driver = org.h2.Driver
db.url = jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM \'classpath:create-db.sql\'
db.username = cost
db.password = cost
entitymanager.packages.to.scan = com.somecompany.cost
hibernate.dialect = org.hibernate.dialect.H2Dialect
hibernate.show_sql = false
hibernate.format_sql = false
应用于标量时返回一个布尔结果。应用于数组时,它返回匹配的元素。在第二个示例中,您使用-match
强制ReadCount
一次通过管道发送多行。当然,您每次都会获得一行数而不仅仅是一行,从而改变了Get-Content
的语义。
要使您的第一个示例正常工作,只需将-match
更改为foreach
。
答案 2 :(得分:0)
-match
表达式返回布尔结果,但也更新特殊变量$matches
。
您可以使用-match
表达式中的where-object
来过滤行,只返回匹配的行。
$myFilteredArray = $myArray | where-object{$_ -match 'execute'}
如果将它用于简单的事情,你也可以使用-like
:
$myFilteredArray = $myArray | where-object{$_ -like '*execute*'}
如果你想要聪明,你也可以使用正则表达式;那样$matches
将保存所有捕获的组(包括一个名为0
的特殊组,其中包含原始行。)
简单示例/纯文本搜索
@(
'line 1 - please '
,'line 2 - execute'
,'line 3 - this'
,'line 4 - script'
) | where-object {$_ -match 'execute'} | foreach-object{
"-Match found the following matches:"
$matches
"The line giving this result was"
$_
}
使用正则表达式/捕获组的示例
@(
'line 1 - please '
,'line 2 - execute'
,'line 3 - this'
,'line 4 - script'
) | where-object {$_ -match '(?<capturedData>.*?)(?: - )execute'} | foreach-object{
"-Match found the following matches:"
$matches
"The line giving this result was"
$_
}
-match
:https://ss64.com/ps/syntax-regex.html -like
,-match
以及其他比较:https://ss64.com/ps/syntax-compare.html