代码如下:
# 获取全部文件路径
$allFilePath = Get-ChildItem -Filter *.txt -Recurse
# 保存匹配成功的文件信息
$illegalFiles = $null
# 循环匹配
foreach($filePath in $allFilePath)
{
$fileContent = Get-Content $filePath.FullName
foreach($lineContent in $fileContent)
{
if($lineContent.IndexOf("匹配字符") -ne -1)
{
# 问题就出在这里
$illegalFiles += $filePath
# 上面这句写法是错误的,我想问的是这里应该怎么写?
break
}
}
}
$illegalFiles = @()
btw 这个例子用 select-string 不是更简单点
$illegalFiles = @()
是对的。
不过你的代码能够简化为
Get-ChildItem -Filter *.txt -Recurse | Select-String -Pattern '匹配字符'
这里有相关的教程 http://www.thomasmaurer.ch/2011/03/powershell-search-for-string-or-grep-for-powershell/