我不是 PowerShell 专家。我试图在文件中搜索多行字符串,但没有得到所需的结果。
这是我的代码:
$search_string = @("This is the first line`nThis is the second line`nThis is the third line")
$file_path = "log.txt"
$ret_string = @(Get-Content -Path $file_path | Where-Object{$_.Contains($search_string)}).Count
Write-Host $ret_string
Run Code Online (Sandbox Code Playgroud)
$ret_string设置为0虽然"log.txt"包含与 完全相同的内容$search_string。
这里有几个问题:
\r\n新行.Contains函数将返回一个布尔值,因此不会帮助您检索计数$search_string不需要是一个数组您可以使用该-Raw参数以字符串形式获取整个文件内容。您最好使用正则表达式在此处进行搜索。尝试:
$search_string = "This is the first line`r`nThis is the second line`r`nThis is the third line"
$file_path = "log.txt"
$ret_string = (Get-Content -raw -Path $file_path | Select-String $search_string -AllMatches | % { $_.matches}).count
Run Code Online (Sandbox Code Playgroud)
$search_string这将返回文件中所有出现的次数
| 归档时间: |
|
| 查看次数: |
3039 次 |
| 最近记录: |