Search code examples
powershellget-childitemselect-object

CSV data from PowerShell Export-Csv contains select clause on first line


I’m pushing data from Get-ChildItem to a csv, via some Where-Object and Select-Object directives as below.

The problem is that the first line of the csv contains the Select clause itself (eg literally { “This part” + $_.AndThisBit }. Not sure why part of my code is leaking into the data?

Get-ChildItem "E:\Some\Path" -Recurse -Include *.msg, *.eml | 
    Where-Object { $_.Name.StartsWith("Confidential") -eq $false } |
    Select-Object { "Fixed-prefix*" + $_.FullName } |
    Export-Csv -Path "C:\another\path\Results.csv" -NoTypeInformation

Solution

  • Select-Object doesn't take ScriptBlocks, as Where-Object does. What you might want is:

    Select-Object -Property @{Name="Prefix"; Expression={"Fixed-prefix*" + $_.FullName}}
    

    To define a custom property with an Expression. That Expression is a ScriptBlock and gets evaluated.