Search code examples
searchpowershellexport-to-excel

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?


Solution

  • 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.