简体   繁体   中英

Powershell script Export-Csv weirdness

I have created a small script to extract all lines of a specified string for a folder and its subfolder. It behaves as expected untill I want to export the lines to excel (csv). At that point it only exports two lines (at least it is the same two lines every single time). In reallity it should have exportet around 40 lines. The working script looks like this:

[string]$pathSource = "D:\Projects\test"
[string]$pathTarget = "D:\Projects\test\searchpattern-sql.csv"

[string[]]$excludeFileTypes = "*.dll","*.pdb","*.gif","*.dat","*.bin","*.msi","*.epi4","*.png","*.tlog","*.gif","*.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

Adding a new pipe with the export cmdlet ( | Export-Csv -path $pathTarget) somehow ruins the search. What am I doing wrong?

Just test this:

[string]$pathSource = "D:\Projects\test"
[string]$pathTarget = "D:\Projects\test\searchpattern-sql.csv"

[string[]]$excludeFileTypes = "*.dll","*.pdb","*.gif","*.dat","*.bin","*.msi","*.epi4","*.png","*.tlog","*.gif","*.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

The $a var just contains the array of lines that I export.

Personally I've found problems using Export-CSV . What I've found working fine is pipe to ConvrtTo-CSV and then to Set-Content or output to file using redirection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM