问题描述
|
我创建了一个小脚本来提取文件夹及其子文件夹的指定字符串的所有行。直到我要将行导出到excel(csv)之前,它的行为均符合预期。此时,它仅导出两行(至少每次都相同)。实际上,它应该有大约40条线的出口。工作脚本如下所示:
[string]$pathSource = \"D:\\Projects\\test\"
[string]$pathTarget = \"D:\\Projects\\test\\searchpattern-sql.csv\"
[string[]]$excludeFileTypes = \"*.dll\",\"*.pdb\",\"*.gif\",\"*.dat\",\"*.bin\",\"*.msi\",\"*.epi4\",\"*.png\",\"*.tlog\",\"*.cache\",\"*.csproj\",\"*.config\",\"*.user\",\"*.txt\"
[string]$searchPattern = \"sqlCommand\"
Get-ChildItem $pathSource -Exclude $excludeFileTypes -Recurse | Select-String $searchPattern | sort-object Path | Select-Object Path,LineNumber,Line
使用export cmdlet添加新管道(| Export-Csv -path $ pathTarget)会以某种方式破坏搜索。我究竟做错了什么?
解决方法
只需测试一下:
[string]$pathSource = \"D:\\Projects\\test\"
[string]$pathTarget = \"D:\\Projects\\test\\searchpattern-sql.csv\"
[string[]]$excludeFileTypes = \"*.dll\",\"*.pdb\",\"*.gif\",\"*.dat\",\"*.bin\",\"*.msi\",\"*.epi4\",\"*.png\",\"*.tlog\",\"*.cache\",\"*.csproj\",\"*.config\",\"*.user\",\"*.txt\"
[string]$searchPattern = \"sqlCommand\"
$a = Get-ChildItem $pathSource -Exclude $excludeFileTypes -Recurse | Select-String $searchPattern | Sort-Object Path | Select-Object Path,LineNumber,Line
$a | Export-Csv yourfile.csv -NoTypeInformation
$ a var仅包含我导出的行数组。
,我个人发现使用Export-CSV
存在问题。我发现可以正常工作的是先将管道连接到ConvrtTo-CSV
,然后再连接到Set-Content
,或者使用重定向输出到文件。